如果您一直遵循這些指南,您應該對 webpack 的一些基礎知識有深入的了解。在我們繼續之前,讓我們來設定一個開發環境,讓我們的作業輕鬆一點。
讓我們從設定 mode
為 'development'
和 title
為 'Development'
開始。
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
+ mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
plugins: [
new HtmlWebpackPlugin({
- title: 'Output Management',
+ title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
當 webpack 捆綁你的原始碼時,追蹤錯誤和警告到它們的原始位置可能會變得困難。例如,如果你將三個原始檔案(a.js
、b.js
和 c.js
)捆綁成一個捆綁(bundle.js
),而其中一個原始檔案包含錯誤,堆疊追蹤會指向 bundle.js
。這並不總是會有幫助,因為你可能想知道錯誤究竟來自哪個原始檔案。
為了讓追蹤錯誤和警告變得更容易,JavaScript 提供了 原始碼對應表,它將你的已編譯程式碼對應回你的原始碼。如果錯誤來自 b.js
,原始碼對應表會明確告訴你。
在原始碼對應表方面,有許多 不同的選項 可用。務必查看它們,以便根據你的需要進行設定。
針對本指南,我們使用 inline-source-map
選項,這對於說明目的來說很好(但對於製作來說則不然)
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
+ devtool: 'inline-source-map',
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
現在讓我們確保我們有一些東西可以除錯,所以我們在我們的 print.js
檔案中建立一個錯誤
src/print.js
export default function printMe() {
- console.log('I get called from print.js!');
+ cosnole.log('I get called from print.js!');
}
執行 npm run build
,它應該編譯成類似這樣的東西
...
[webpack-cli] Compilation finished
asset index.bundle.js 1.38 MiB [emitted] (name: index)
asset print.bundle.js 6.25 KiB [emitted] (name: print)
asset index.html 272 bytes [emitted]
runtime modules 1.9 KiB 9 modules
cacheable modules 530 KiB
./src/index.js 406 bytes [built] [code generated]
./src/print.js 83 bytes [built] [code generated]
./node_modules/lodash/lodash.js 530 KiB [built] [code generated]
webpack 5.4.0 compiled successfully in 706 ms
現在在你的瀏覽器中開啟產生的 index.html
檔案。按一下按鈕,並在你的主控台中尋找顯示錯誤的位置。錯誤應該類似這樣
Uncaught ReferenceError: cosnole is not defined
at HTMLButtonElement.printMe (print.js:2)
我們可以看到錯誤還包含對檔案(print.js
)和發生錯誤的行號(2)的參考。這很好,因為現在我們確切知道在哪裡尋找以修復問題。
每次你想要編譯你的程式碼時,手動執行 npm run build
會很快變成一種麻煩。
webpack 中有幾個不同的選項可供使用,它們可以幫助你每當你的程式碼變更時自動編譯你的程式碼
在大部分情況下,您可能會想使用 webpack-dev-server
,但讓我們探討一下以上所有選項。
您可以指示 webpack 「監控」依賴關係圖中的所有檔案是否有變更。如果這些檔案中的其中一個檔案已更新,程式碼將會重新編譯,因此您不必手動執行完整建置。
讓我們新增一個 npm 指令,它會啟動 webpack 的監控模式
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^4.5.0",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
現在從命令列執行 npm run watch
,並查看 webpack 如何編譯您的程式碼。您會看到它不會退出命令列,因為指令目前正在監控您的檔案。
現在,當 webpack 正在監控您的檔案時,讓我們移除我們先前引入的錯誤
src/print.js
export default function printMe() {
- cosnole.log('I get called from print.js!');
+ console.log('I get called from print.js!');
}
現在儲存您的檔案並查看終端機視窗。您應該會看到 webpack 自動重新編譯已變更的模組!
唯一的缺點是您必須重新整理瀏覽器才能看到變更。如果也能自動執行這項操作會好得多,因此讓我們嘗試 webpack-dev-server
,它將執行這項操作。
webpack-dev-server
為您提供一個基本的網路伺服器,以及使用即時重新載入的功能。讓我們設定它
npm install --save-dev webpack-dev-server
變更您的設定檔,告訴開發伺服器在哪裡尋找檔案
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
devtool: 'inline-source-map',
+ devServer: {
+ static: './dist',
+ },
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
+ optimization: {
+ runtimeChunk: 'single',
+ },
};
這會告訴 webpack-dev-server
在 localhost:8080
上提供 dist
目錄中的檔案。
讓我們新增一個腳本,以便輕鬆地執行開發伺服器
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
+ "start": "webpack serve --open",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^4.5.0",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
現在,我們可以從命令列執行 npm start
,然後我們將會看到我們的瀏覽器自動載入我們的頁面。如果您現在變更任何原始檔案並儲存它們,網頁伺服器將會在程式碼編譯後自動重新載入。試試看吧!
webpack-dev-server
附帶許多可設定的選項。前往 文件 以了解更多資訊。
webpack-dev-middleware
是包裝器,它會將 webpack 處理的檔案發射到伺服器。這在 webpack-dev-server
內部使用,但如果需要,它可以作為獨立的套件提供,以便進行更多自訂設定。我們將來看一個結合 webpack-dev-middleware
和 express 伺服器的範例。
讓我們安裝 express
和 webpack-dev-middleware
,以便開始
npm install --save-dev express webpack-dev-middleware
現在,我們需要調整我們的 webpack 設定檔,以確保中間軟體可以正常運作
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
devtool: 'inline-source-map',
devServer: {
static: './dist',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
+ publicPath: '/',
},
};
publicPath
也將在我們的伺服器腳本中使用,以確保檔案正確提供給 https://127.0.0.1:3000
。稍後我們會指定埠號。下一步是設定我們的自訂 express
伺服器
專案
webpack-demo
|- package.json
|- package-lock.json
|- webpack.config.js
+ |- server.js
|- /dist
|- /src
|- index.js
|- print.js
|- /node_modules
server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
})
);
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
現在新增一個 npm 腳本,讓執行伺服器變得更簡單
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"start": "webpack serve --open",
+ "server": "node server.js",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"express": "^4.17.1",
"html-webpack-plugin": "^4.5.0",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0",
"webpack-dev-middleware": "^4.0.2",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
現在在您的終端機上執行 npm run server
,它應該會提供類似這樣的輸出
Example app listening on port 3000!
...
<i> [webpack-dev-middleware] asset index.bundle.js 1.38 MiB [emitted] (name: index)
<i> asset print.bundle.js 6.25 KiB [emitted] (name: print)
<i> asset index.html 274 bytes [emitted]
<i> runtime modules 1.9 KiB 9 modules
<i> cacheable modules 530 KiB
<i> ./src/index.js 406 bytes [built] [code generated]
<i> ./src/print.js 83 bytes [built] [code generated]
<i> ./node_modules/lodash/lodash.js 530 KiB [built] [code generated]
<i> webpack 5.4.0 compiled successfully in 709 ms
<i> [webpack-dev-middleware] Compiled successfully.
<i> [webpack-dev-middleware] Compiling...
<i> [webpack-dev-middleware] assets by status 1.38 MiB [cached] 2 assets
<i> cached modules 530 KiB (javascript) 1.9 KiB (runtime) [cached] 12 modules
<i> webpack 5.4.0 compiled successfully in 19 ms
<i> [webpack-dev-middleware] Compiled successfully.
現在啟動您的瀏覽器並前往 https://127.0.0.1:3000
。您應該會看到您的 webpack 應用程式正在執行並運作!
在使用自動編譯您的程式碼時,您可能會在儲存檔案時遇到問題。有些編輯器具有「安全寫入」功能,可能會干擾重新編譯。
若要停用某些常見編輯器中的此功能,請參閱以下清單
atomic_save: 'false'
新增到您的使用者偏好設定。偏好設定 > 外觀與行為 > 系統設定
中的「使用安全寫入」。:set backupcopy=yes
新增到您的設定。現在您已學會如何自動編譯您的程式碼並執行開發伺服器,您可以檢閱下一份指南,其中將涵蓋程式碼拆分。