[webpack3.8.1]Guides-2-getting-started(入門)

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.html

       如你所知,webpack被用來編譯JavaScript模塊。只要你安裝了它,你就能夠經過CLI或者API來調用它的接口。若是你是個萌新,請你先閱讀一下核心概念對比以瞭解爲何你能夠將其用於我們社區之外的工具。node

Basic Setup (基礎安裝)

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

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.json

       在這個示例中,<script>標籤之間存在隱式的依賴關係。咱們的index.js文件依賴於lodash,它在運行以前就被包含在頁面中。這是由於index.js歷來沒有聲明須要lodash; 它只是假定全局變量_存在。windows

There are problems with managing JavaScript projects this way:api

       以這種方式管理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翻譯地更好一些。固然,也在這裏建議全部但願學習新鮮技術的小夥伴,不要懼怕讀官方教學文檔,就和我同樣,一點一點地精心翻譯,必定能夠有所成長!反正我是有這個感受,我來到北京以後就感受這個世界其實並不須要任何偉人,只須要以偉大的方式去作事的人,真的,不管你作什麼,別人記不記得你的好,管他呢,你已經成就了本身。物理學真正的發展都是由於樂趣,咱們的人生不也是一場精美的遊戲麼?

相關文章
相關標籤/搜索