Setting Up Webpack Configuration

我們必須告訴 Webpack 如何處理我們剛剛設定的 assets,所以就必須要設定 webpack.config.js。

為了簡單,我們使用 html-webpack-plugin 來產生 index.html,安裝 plugin:

npm i html-webpack-plugin --save-dev

webpack.config.js

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

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build')
};

module.exports = {
  // Entry accepts a path or an object of entries.
  // We'll be using the latter form given it's
  // convenient with more complex configurations.
  entry: {
    app: PATHS.app
  },
  output: {
    path: PATHS.build,
    filename: '[name].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo'
    })
  ]
};

entry 的路徑可以使用絕對路徑,但最好還是使用相對路徑。

文中提到 context ,但用法還不清楚,先記起來。

執行 node_modules/.bin/webpack,就可以看到以下資訊:

Hash: 2a7a7bccea1741de9447
Version: webpack 1.13.0
Time: 813ms
     Asset       Size  Chunks             Chunk Names
    app.js    1.69 kB       0  [emitted]  app
index.html  157 bytes          [emitted]
   [0] ./app/index.js 80 bytes {0} [built]
   [1] ./app/component.js 136 bytes {0} [built]
Child html-webpack-plugin for "index.html":
        + 3 hidden modules

以下為原文解釋上面的資訊代表什麼,懶得翻了,直接看原文吧XD

  • Hash: 2a7a7bccea1741de9447 - The hash of the build. You can use this to invalidate assets through [hash] placeholder. We'll discuss hashing in detail at the Adding Hashes to Filenames chapter.
  • Version: webpack 1.13.0 - Webpack version.
  • Time: 813ms - Time it took to execute the build.
  • app.js 1.69 kB 0 [emitted] app - Name of the generated asset, size, the ids of the chunks into which it is related, status information telling how it was generated, name of the chunk.
  • [0] ./app/index.js 80 bytes {0} [built] - The id of the generated asset, name, size, entry chunk id, the way it was generated.
  • Child html-webpack-plugin for "index.html": - This is plugin related output. In this case html-webpack-plugin is doing output of its own.
  • + 3 hidden modules - This tells you that Webpack is omitting some output, namely modules within node_modules and similar directories. You can run Webpack using webpack --display-modules to display this information. See Stack Overflow for an expanded explanation.

可以安裝 Serve 工具啟動伺服器查看 build/:npm i serve -g 例如: serve ./build/,就可以在 localhost:3000 看到網頁 可以使用 --port 改變 port

results matching ""

    No results matching ""