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.html
如你所知,webpack被用来编译JavaScript模块。只要你安装了它,你就能够经过CLI或者API来调用它的接口。若是你是个萌新,请你先阅读一下核心概念和对比以了解为何你能够将其用于我们社区之外的工具。node
First let's create a directory, initialize npm, and install webpack locally:webpack
首先,咱们建立一个文件夹,初始化npm
,而后以本地化的方式安装webpack:git
mkdir webpack-demo && cd webpack-demo npm init -y npm install --save-dev webpack
P.S.:在中国,咱们能够很是幸福地使用 cnpmgithub
Now we'll create the following directory structure and contents:web
如今咱们将建立如下目录结构和内容:npm
webpack-demo |- package.json + |- index.html + |- /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());
<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.json
在这个示例中,<script>
标签之间存在隐式的依赖关系。咱们的index.js
文件依赖于lodash
,它在运行以前就被包含在页面中。这是由于index.js
历来没有声明须要lodash
; 它只是假定全局变量_
存在。windows
There are problems with managing JavaScript projects this way:api
以这种方式管理JavaScript
项目,存在以下的问题:
Let's use webpack to manage these scripts instead.
让咱们换用webpack来管理这些脚本吧!
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程序产出的精简、优化后的代码,它最终被浏览器加载:
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脚本...
+ 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
文件方式啦:
<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'。
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.
import
和export
语句已经在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作了这个,这是多么地机智!除了import
和export
,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将不会更改任何代码除了import
、export
语句们。若是你正在使用ES2015
的特性,你必定要确认一下,能够经过转译器,好比Babel
或者Bublé
,经由webpack的加载系统能转译成功。
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
选项的配置文件吧:
webpack-demo |- package.json + |- webpack.config.js |- /dist |- index.html |- /src |- index.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
更加灵活地进行配置。咱们能够指定加载的规则、组件,解析选项,还有不少其它的加强功能。戳这里了解更多的内容吧!
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
:
{ ... "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
。
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翻译地更好一些。固然,也在这里建议全部但愿学习新鲜技术的小伙伴,不要惧怕读官方教学文档,就和我同样,一点一点地精心翻译,必定能够有所成长!反正我是有这个感受,我来到北京以后就感受这个世界其实并不须要任何伟人,只须要以伟大的方式去作事的人,真的,不管你作什么,别人记不记得你的好,管他呢,你已经成就了本身。物理学真正的发展都是由于乐趣,咱们的人生不也是一场精美的游戏么?