webpack 4 入門指南 系列四(輸出管理篇)

本教程使用基于資源管理教程的代碼示例

  • 到目前為止我們手動在index.html中包含所有的資源,但是隨著應用變得復雜或者一旦在文件名中使用哈希并輸出多個bundle,那是很難繼續手動管理index.html文件。但是這里有一些插件可以使這些管理變得簡單。

準備工作

  • 首先稍微調整一下我們的工程

project

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- /dist
  |- /src
    |- index.js
+   |- print.js
  |- /node_modules
  • src/print.js中加一些邏輯

src/print.js

export default function printMe() {
  console.log('I get called from print.js!');
}
  • src/index.js中使用該函數

src/index.js

  import _ from 'lodash';
+ import printMe from './print.js';

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

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

+   btn.innerHTML = 'Click me and check the console!';
+   btn.onclick = printMe;
+
+   element.appendChild(btn);

    return element;
  }

  document.body.appendChild(component());
  • 同時更新下dist/index.html文件,準備然webpack拆分入口

dist/index.html

  <!doctype html>
  <html>
    <head>
-     <title>Asset Management</title>
+     <title>Output Management</title>
+     <script src="./print.bundle.js"></script>
    </head>
    <body>
-     <script src="./bundle.js"></script>
+     <script src="./app.bundle.js"></script>
    </body>
  </html>
  • 接下來調整配置文件。把src/print.js添加為新的入口節點(print),同樣改變output,以便它能根據入口節點名稱動態生成bundle的名字。

webpack.config.js

  const path = require('path');

  module.exports = {
-   entry: './src/index.js',
+   entry: {
+     app: './src/index.js',
+     print: './src/print.js'
+   },
    output: {
-     filename: 'bundle.js',
+     filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };
  • 現在執行構建命令 npm run build
Hash: aa305b0f3373c63c9051
Version: webpack 3.0.0
Time: 536ms
          Asset     Size  Chunks                    Chunk Names
  app.bundle.js   545 kB    0, 1  [emitted]  [big]  app
print.bundle.js  2.74 kB       1  [emitted]         print
   [0] ./src/print.js 84 bytes {0} {1} [built]
   [1] ./src/index.js 403 bytes {0} [built]
   [3] (webpack)/buildin/global.js 509 bytes {0} [built]
   [4] (webpack)/buildin/module.js 517 bytes {0} [built]
    + 1 hidden module
  • 可以看到webpack生成了print.bundle.jsapp.bundle.js文件,就是我們也在index.html中指定的。如果你在瀏覽器打開index.html,你點擊按鈕就會看到會發生什么。

  • 但是如果我們改變其中一個入口節點的名稱或者添加一個新節點會發生什么?生成的bundles會在構建時重新命名,但是index.html仍然會引用舊的名字。讓我們用HtmlWebpackPlugin修復這個問題吧。

設置 HtmlWebpackPlugin

  • 首先安裝插件并調整webpack.config.js文件
npm install --save-dev html-webpack-plugin

webpack.config.js

  const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management'
+     })
+   ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };
  • 在我們構建之前,你應該了解HtmlWebpackPlugin默認會生成它自己的index.html文件,即使在dist目錄已經有一個了。這意味著它將用新生成的index.html替換我們自己的。讓我們看看構建之后會發生什么:
Hash: 81f82697c19b5f49aebd
Version: webpack 2.6.1
Time: 854ms
           Asset       Size  Chunks                    Chunk Names
 print.bundle.js     544 kB       0  [emitted]  [big]  print
   app.bundle.js    2.81 kB       1  [emitted]         app
      index.html  249 bytes          [emitted]
   [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 172 bytes {1} [built]
   [4] multi lodash 28 bytes {0} [built]
Child html-webpack-plugin for "index.html":
       [0] ./~/lodash/lodash.js 540 kB {0} [built]
       [1] ./~/html-webpack-plugin/lib/loader.js!./~/html-webpack-plugin/default_index.ejs 538 bytes {0} [built]
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
  • 如果你用編輯器打開index.html,你會看到HtmlWebpackPlugin已經創建一個新的文件并且所有的bundles都自動添加進來了。

清理 /dist 目錄

  • 通過之前的教程和代碼示例,你可能注意到/dist文件是非常混亂的。Webpack會為你生成文件并放到/dist目錄中,但是你很難追蹤哪一個文件才是你的項目在使用的。

  • 通常,在每一次構建之前,清理/dist目錄是個好習慣,這樣就只有需要使用的文件才會生成。我們來了解一下。

  • 有一個專門用來管理這個的插件clean-webpack-plugin,我們安裝和配置一下

npm install clean-webpack-plugin --save-dev

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };
  • 現在重新構建一下并檢查一下/dist目錄。如果一切正常,你應該只會看到構建生成的文件,不再有老的文件了。

清單

  • 你可能想了解webpack和插件是怎么知道哪些文件是需要生成的。答案就是清單,webpack用來跟蹤所有的模塊是如何映射輸出bundle的。如果你對webpack管理output的其他方式感興趣,那么清單是很好的出發點。

  • 可以使用WebpackManifestPlugin將清單數據提取到json文件中,以便于使用。

總結

  • 現在,您已經了解了如何動態地將捆包添加到HTML中,接下來讓我們深入研究開發教程。或者,如果您想深入研究更高級的主題,我們建議您去代碼分割指南
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容