環境: win10, webpack v3.5.6, node v8.4, npm v5.3.html
新建一個項目目錄demo
, 在當前目錄執行以下命令:node
npm init -y npm install --save-dev webpack npm install --save lodash
根據以下目錄結構建立文件:webpack
demo |- package.json + |- webpack.config.js |- /dist |- index.html |- /src |- index.js
新版npm會自動建立package-lock.json
dist是distribution code的縮寫, 用來存放生產環境的代碼.web
webpack.config.js 內容以下npm
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };
dist/index.html 內如以下json
<html> <head> <title>Getting Started</title> </head> <body> <script src="bundle.js"></script> </body> </html>
src/index.js 內容以下app
import _ from 'lodash'; function component() { var element = document.createElement('div'); // Lodash, now imported by this script element.innerHTML = _.join(['Hello', 'webpack'], ' '); return element; } document.body.appendChild(component());
在package.json中添加以下內容ide
"scripts": { "build": "webpack" }
執行npm run build
, 將會在dist
目錄下生成bundle.js
. 成功執行後將輸出如下內容:測試
sheng@SHENG-LAPTOP D:\Asheng_IDE\FrontEnd\study_tree\webpack\demo > npm run build > demo@1.0.0 build D:\Asheng_IDE\FrontEnd\study_tree\webpack\demo > webpack Hash: bf97d2bdc70ce2f70877 Version: webpack 3.5.6 Time: 386ms Asset Size Chunks Chunk Names bundle.js 544 kB 0 [emitted] [big] main [0] ./src/index.js 263 bytes {0} [built] [2] (webpack)/buildin/global.js 509 bytes {0} [built] [3] (webpack)/buildin/module.js 517 bytes {0} [built] + 1 hidden module
此時, 在dist
目錄下的2個文件: index.html
和 bundle.js
即爲打包的在生產環境中使用
的文件, 雙擊index.html
可直接運行.ui
https://webpack.js.org/guides/getting-started/