Getting Started

As you may already know, webpack is used to compile JavaScript modules. Once installed, you can interface with webpack either from its CLI or API. If you're still new to webpack, please read through the core concepts and this comparison to learn why you might use it over the other tools that are out in the community.

       如你所知,webpack被用来编译JavaScript模块。只要你安装了它,你就可以通过CLI或者API来调用它的接口。如果你是个萌新,请你先阅读一下核心概念对比以了解为什么你可以将其用于咱们社区以外的工具。

Basic Setup (基础安装)

First let's create a directory, initialize npm, and install webpack locally:

       首先,我们创建一个文件夹,初始化npm,然后以本地化的方式安装webpack:

mkdir webpack-demo && cd webpack-demo
npm init -y
npm install --save-dev webpack

P.S.:在中国,我们可以非常幸福地使用   cnpm

Now we'll create the following directory structure and contents:

       现在我们将创建以下目录结构和内容:

project

  webpack-demo
  |- package.json
+ |- index.html
+ |- /src
+   |- index.js

src/index.js

function component() {
  var element = document.createElement('div');

  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

index.html

<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>

In this example, there are implicit dependencies between the <script> tags. Our index.js file depends on lodash being included in the page before it runs. This is because index.js never declared a need for lodash; it just assumes that the global variable _ exists.

       在这个示例中,<script>标签之间存在隐式的依赖关系。我们的index.js文件依赖于lodash,它在运行之前就被包含在页面中。这是因为index.js从来没有声明需要lodash; 它只是假定全局变量_存在。

There are problems with managing JavaScript projects this way:

       以这种方式管理JavaScript项目,存在如下的问题:

  • JS脚本对于外部库的依赖并不是那么显而易见
  • 如果一个依赖丢失了或者引用的顺序不对(比如某些JS以来JQuery,而JQuery的引用放在了该库的后面,就会发生各种错误),则应用程序将无法正常运行
  • 如果一个依赖引用了,但是并没有使用,浏览器也会加载它(这当然是一种浪费)。

Let's use webpack to manage these scripts instead.

       让我们换用webpack来管理这些脚本吧!

Creating a Bundle (创建一个捆绑JS文件)

First we'll tweak our directory structure slightly, separating the "source" code (/src) from our "distribution" code (/dist). The "source" code is the code that we'll write and edit. The "distribution" code is the minimized and optimized output of our build process that will eventually be loaded in the browser:

       首先,我们将微调一下我们的目录结构,将我们的源代码/src目录从发行版代码/dist目录中分离出来。/src中的代码是我们将要编辑的;/dist中的代码是我们的build程序产出的精简、优化后的代码,它最终被浏览器加载:

project

  webpack-demo
  |- package.json
+ |- /dist
+   |- index.html
- |- index.html
  |- /src
    |- index.js

To bundle the lodash dependency with index.js, we'll need to install the library locally...

       为了捆绑index.js和它的依赖lodash,我们将需要安装本地库。

npm install --save lodash

       现在轮到JS脚本...

src/index.js

+ import _ from 'lodash';
+
  function component() {
    var element = document.createElement('div');

-   // Lodash, currently included via a script, is required for this line to work
+   // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
  }

  document.body.appendChild(component());

P.S.:左边的    和    的意思是对于之前的  index.js  文件,我们新增了哪一句,减少了哪一句。

Now, since we'll be bundling our scripts, we have to update our index.html file. Let's remove the lodash <script>, as we now import it, and modify the other <script> tag to load the bundle, instead of the raw /src file:

       现在,由于我们将要打包我们的脚本了,我们不得不“升级一下”我们的index.html文件。让我们移除lodash的<script>标签,现在我们再导入呀,就直接用<script>标签来加载捆绑后的js,就不用原始的/src文件方式啦:

dist/index.html

  <html>
   <head>
     <title>Getting Started</title>
-    <script src="https://unpkg.com/lodash@4.16.6"></script>
   </head>
   <body>
-    <script src="./src/index.js"></script>
+    <script src="bundle.js"></script>
   </body>
  </html>

In this setup, index.js explicitly requires lodash to be present, and binds it as _ (no global scope pollution). By stating what dependencies a module needs, webpack can use this information to build a dependency graph. It then uses the graph to generate an optimized bundle where scripts will be executed in the correct order.

       在本次环境搭建中,index.js非常明确地需要lodash,而且以_来绑定了它(没有全局作用域污染)。通过声明一个模块所需要的各种依赖,webpack可以使用这个信息来构建一个“依赖关系图”。随后,它使用这个图来产生一个优化后的捆绑文件,在这个捆绑文件中,所有的脚本都将会被以正确的顺序执行(即不会出现由于声明顺序而导致莫名其妙失败的错误)。

P.S.;setup

With that said, let's run webpack with our script as the entry point and bundle.js as the output:

       就像我说的,让我们以我们的JS脚本为entry point 以我们的bundle.js为输出运行webpack吧:

./node_modules/.bin/webpack src/index.js dist/bundle.js

P.S.:以上为命令,以下为控制台运行结果输出,特分离此二者以明晰。

Hash: ff6c1d39b26f89b3b7bb
Version: webpack 2.2.0
Time: 385ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 278 bytes {0} [built]

Your output may vary a bit, but if the build is successful then you are good to go.

       你的输出可能有一点点不同,不过只要你成功了,就继续往下面看吧!

Open index.html in your browser and, if everything went right, you should see the following text: 'Hello webpack'.

       在浏览器中打开index.html,然后,如果一切顺利的话,你将会看到这样的文字:'Hello webpack'。

Modules (模块)

The import and export statements have been standardized in ES2015. Although they are not supported in most browsers yet, webpack does support them out of the box.

       importexport语句已经在ES2015中成为规范。即算它们还不被大部分浏览器支持,webpack着实地支持了它们一把,使它们开箱即用!

Behind the scenes, webpack actually "transpiles" the code so that older browsers can also run it. If you inspect dist/bundle.js, you might be able to see how webpack does this, it's quite ingenious! Besides import and export, webpack supports various other module syntaxes as well, see Module API for more information.

       在这动人的一幕幕的背后,webpack确实转译了代码(比如一些ES6语法某些浏览器并不支持,webpack会优先将这些代码转成老旧的js代码),以便于浏览器能够运行它。如果你监视了dist/bundle.js,你可能会看到webpack做了这个,这是多么地机智!除了importexport,webpack也支持多种多样的其它的模块语法,戳这里了解更多吧!

P.S.:transpile  transcompile   这里恒宝想吐槽一下国外的武林高手们,干嘛造一些奇怪的词汇呀……已经有了transcompile这么容易理解的词汇,转换(transform)和编译(compile)的混搭嘛!又仓颉了一个transpile……不累吗?在这里,我把这个词汇翻译成了转译,大家可以类比生物学中的基因的转录、翻译,当然不要混淆这两个概念,只是有一点相似之处。还有的人翻译为转码,只要理解意思就可以……

Note that webpack will not alter any code other than import and export statements. If you are using other ES2015 features, make sure to use a transpiler such as Babel or Bublé via webpack's loader system.

       需要注意的是,webpack将不会更改任何代码除了importexport语句们。如果你正在使用ES2015的特性,你一定要确认一下,可以通过转译器,比如Babel或者Bublé,经由webpack的加载系统能转译成功。

Using a Configuration (使用配置的方式)

Most projects will need a more complex setup, which is why webpack supports a configuration file. This is much more efficient than having to type in a lot of commands in the terminal, so let's create one to replace the CLI options used above:

       大多数项目都需要更加复杂的基础环境的搭建,这就是为什么webpack支持大家使用一个配置文件来规定一些依赖。这比在命令行里敲敲敲要有效率得多了,所以,让我们来创建一个替代CLI选项的配置文件吧:

project

  webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Now, let's run the build again but instead using our new configuration:

       现在,让我们重新编译,不过这一次,我们用我们的配置文件:

./node_modules/.bin/webpack --config webpack.config.js
Hash: ff6c1d39b26f89b3b7bb
Version: webpack 2.2.0
Time: 390ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 278 bytes {0} [built]

Note that when calling webpack via its path on windows, you must use backslashes instead, e.g. node_modules.binwebpack --config webpack.config.js.

       注意了啊,当我们在windows系统的命令行上调用webpack的时候,你必须使用反斜杠。

P.S.:其实这一句话多虑了,我们一般都会使用一些工具,使得windows上可以运行Linux上的bash。最常用的竟然是git bash,哈哈,可能是因为方便吧。

If a webpack.config.js is present, the webpack command picks it up by default. We use the --config option here only to show that you can pass a config of any name. This will be useful for more complex configurations that need to be split into multiple files.

       如果您给出了webpack.config.js,webpack命令将会默认读取它。我们在这里使用 --config 选项只是为了展现你可以给配置文件取一个你喜欢的名字。(比如:hengbao.config.js)

A configuration file allows far more flexibility than simple CLI usage. We can specify loader rules, plugins, resolve options and many other enhancements this way. See the configuration documentation to learn more.

       一个配置文件可以允许比CLI更加灵活地进行配置。我们可以指定加载的规则、组件,解析选项,还有很多其它的增强功能。戳这里了解更多的内容吧!

NPM Scripts

Given it's not particularly fun to run a local copy of webpack from the CLI, we can set up a little shortcut. Let's adjust our package.json by adding an npm script:

       鉴于从CLI运行webpack的本地副本并不是特别有趣,我们可以设置一个小捷径。让我们通过添加一个npm脚本来调整我们的package.json

package.json

{
  ...
  "scripts": {
    "build": "webpack"
  },
  ...
}

Now the npm run build command can be used in place of the longer commands we used earlier. Note that within scripts we can reference locally installed npm packages by name instead of writing out the entire path. This convention is the standard in most npm-based projects and allows us to directly call webpack, instead of ./node_modules/.bin/webpack

       现在这个npm run build命令可以用来代替我们之前使用的较长的命令。请注意,scripts我们可以通过名称来引用本地安装的npm包,而不是写出整个路径。这个惯例是基于npm的项目标准,而且允许我们直接调用webpack,而不是./node_modules/.bin/webpack(找到webpack主程序所在路径才能执行)。

Now run the following command and see if your script alias works:

       现在,我们执行下面的命令,如果你的脚本别名起作用了的话:

npm run build
Hash: ff6c1d39b26f89b3b7bb
Version: webpack 2.2.0
Time: 390ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 278 bytes {0} [built]

Custom parameters can be passed to webpack by adding two dashes between the npm run build command and your parameters, e.g. npm run build -- --colors.

       自定义参数可以通过在npm run build命令和参数之间添加两个破折号传递给webpack ,例如npm run build -- --colors

Conclusion (总结)

Now that you have a basic build together you should move on to the next guide Asset Management to learn how to manage assets like images and fonts with webpack. At this point, your project should look like this:

       现在,你拥有一个基础的搭建项目的能力了,你应当去下一个指南性帮助“资源管理”去学习怎么样用webpack管理资源,就比如说,图片呀,字体呀……在咱们这一趴呀,你的项目应该已经像这个样子啦:

webpack-demo
|- package.json
|- webpack.config.js
|- /dist
  |- bundle.js
  |- index.html
|- /src
  |- index.js
|- /node_modules

If you're using npm 5, you'll probably also see a package-lock.json file in your directory.

       如果你使用了npm5,你还将看到你的目录中多一个package-lock.json

If you want to learn more about webpack's design, you can check out the basic concepts and configuration pages. Furthermore, the API section digs into the various interfaces webpack offers.

       如果你想学习更多的关于webpack的设计,你可以检出我们的基本概念和配置的页。更多哒,API部分,将会更加深入地探讨webpack提供的多种多样的接口。

P.S.:好累,第一次翻译这么长的guide,相信自己翻译多了就习惯了,每一次翻译的时候都会自豪的使用Google翻译一下,当然是自己翻译完了再对比Google的翻译,有时候自己翻译地更好一些,有时候Google翻译地更好一些。当然,也在这里建议所有希望学习新鲜技术的小伙伴,不要害怕读官方教学文档,就和我一样,一点一点地精心翻译,一定可以有所成长!反正我是有这个感觉,我来到北京之后就感觉这个世界其实并不需要任何伟人,只需要以伟大的方式去做事的人,真的,无论你做什么,别人记不记得你的好,管他呢,你已经成就了自己。物理学真正的发展都是因为乐趣,我们的人生不也是一场精美的游戏么?


hengbao
22 声望2 粉丝

消极的心态限制潜能发挥