资讯专栏INFORMATION COLUMN

[译]教程:如何使用Rollup打包样式文件并添加LiveReload

garfileo / 2801人阅读

摘要:通过这个教程学习如何使用打包工具配合来取代或处理样式文件。使用这个命令安装插件更新。如果你没有项目的副本,你可以通过这条命令克隆在结束这个状态下的项目为添加监听插件。在代码块内,添加如下内容简单起见我省略了文件的大部分内容

通过这个教程学习如何使用JavaScript打包工具Rollup配合PostCSS来取代Grunt或Gulp处理样式文件。

上一篇文章中,我们完成了使用Rollup打包前端JavaScript入门。

这篇文章包含Part IIPart III

Part II会继续在上次的项目中进行,为Rollup添加处理样式的能力,使用PostCSS进行一些转换,让我们能使用更简单的变量写法和嵌套规则等语法糖。

然后完成Part III,圆满结束。第三部分将为项目添加文件监听和LiveReload,这样每当文件变化时就不用再手动地打包bundle文件了。

准备工作

我们会在上周的项目基础上继续进行,因此如果你还没有看上一节,推荐你先看一下。

NOTE: 如果你没有项目的副本,你可以通过这条命令克隆在Part I结束这个状态下的项目:git clone -b part-2-starter --single-branch https://github.com/jlengstorf/learn-rollup.git

Part II:如何在下一代应用中使用Rollup.js: PostCSS

你可以轻松地处理CSS并注入到文档的head中,这取决于你的项目如何配置,也是Rollup另一个优点。

另外,所有的构建过程都在一个地方,降低了开发流程的复杂度 - 这对我们很有帮助,尤其是在团队协作时。

不过糟糕的是,我们使得样式依赖JavaScript,并且在无样式HTML在样式注入前会产生一个短暂的闪烁。这对有些项目来说是无法接受的,并且应该通过像使用PostCSS提取等方式解决。

既然这篇文章是关于Rollup的,那么:来吧。让我们使用Rollup!

STEP 0: 在main.js中加载样式。

如果你之前从来没用过构建工具,可能感觉这样有点怪,但请跟着我继续。为了在文档中使用样式,我们不会像平常那样使用标签,取而代之,我们将在main.min.js中使用import语句。

现在在src/scripts/main.js开头加载样式:

+ // Import styles (automatically injected into ).
+ import "../styles/main.css";

  // Import a couple modules for testing.
  import { sayHelloTo } from "./modules/mod1";
  import addArray from "./modules/mod2";

  // Import a logger for easier debugging.
  import debug from "debug";
  const log = debug("app:log");

  // The logger should only be disabled if we’re not in production.
  if (ENV !== "production") {

    // Enable the logger.
    debug.enable("*");
    log("Logging is enabled!");
  } else {
    debug.disable();
  }

  // Run some functions from our imported modules.
  const result1 = sayHelloTo("Jason");
  const result2 = addArray([1, 2, 3, 4]);

  // Print the results on the page.
  const printTarget = document.getElementsByClassName("debug__output")[0];

  printTarget.innerText = `sayHelloTo("Jason") => ${result1}

`;
  printTarget.innerText += `addArray([1, 2, 3, 4]) => ${result2}`;
STEP 1: 安装PostCSS Rollup插件。

首先需要Rollup PostCSS插件,使用如下命令安装:

npm install --save-dev rollup-plugin-postcss

STEP 2: 更新rollup.config.js.

然后,添加插件到rollup.config.js:

  // Rollup plugins
  import babel from "rollup-plugin-babel";
  import eslint from "rollup-plugin-eslint";
  import resolve from "rollup-plugin-node-resolve";
  import commonjs from "rollup-plugin-commonjs";
  import replace from "rollup-plugin-replace";
  import uglify from "rollup-plugin-uglify";
+ import postcss from "rollup-plugin-postcss";

  export default {
    entry: "src/scripts/main.js",
    dest: "build/js/main.min.js",
    format: "iife",
    sourceMap: "inline",
    plugins: [
+     postcss({
+       extensions: [ ".css" ],
+     }),
      resolve({
        jsnext: true,
        main: true,
        browser: true,
      }),
      commonjs(),
      eslint({
        exclude: [
          "src/styles/**",
        ]
      }),
      babel({
        exclude: "node_modules/**",
      }),
      replace({
        ENV: JSON.stringify(process.env.NODE_ENV || "development"),
      }),
      (process.env.NODE_ENV === "production" && uglify()),
    ],
  };
看一下生成的bundle。

现在我们已经能够处理样式了,可以看一下新生成的bundle,看看它是如何工作的。

运行./node_modules/.bin/rollup -c,然后看一下生成的build/js/main.min.js,在文件开头几行,可以看到一个名叫__$styleInject()的新函数:

function __$styleInject(css) {
  css = css || "";
  var head = document.head || document.getElementsByTagName("head")[0];
  var style = document.createElement("style");
  style.type = "text/css";
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  head.appendChild(style);
}
__$styleInject("/* Styles omitted for brevity... */");

简单地说,这个函数创建了一个