HtmlWebpackPlugin
簡化了建立 HTML 檔案以提供 webpack 程式包的流程。這對於在檔名中包含雜湊值且每次編譯都會變更的 webpack 程式包特別有用。你可以讓外掛為你產生 HTML 檔案、使用 lodash 範本 提供你自己的範本,或使用你自己的 載入器。
npm install --save-dev html-webpack-plugin
外掛會為你產生一個 HTML5 檔案,其中包含所有 webpack 程式包,並在主體中使用 script
標籤。將外掛新增到你的 webpack 組態,如下所示
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js',
},
plugins: [new HtmlWebpackPlugin()],
};
這會產生一個包含以下內容的檔案 dist/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>webpack App</title>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>
如果你有多個 webpack 進入點,它們都會包含在產生的 HTML 中的 <script>
標籤中。
如果你在 webpack 的輸出中有任何 CSS 資源(例如,使用 MiniCssExtractPlugin 萃取的 CSS),則這些資源會包含在產生的 HTML 的 <head>
元素中的 <link>
標籤中。
有關所有組態選項,請參閱 外掛文件。
此外掛程式支援附加元件。如需清單,請參閱文件。