第一種方式:html-webpack-plugin(插件的基本作用就是生成html文件。原理很簡單:)
使用 npm 安裝這個插件
npm install html-webpack-plugin@2 --save-dev
這個插件可以幫助生成 HTML 文件,在 body 元素中,使用 script 來包含所有你的 webpack bundles,只需要在你的 webpack 配置文件中如下配置:
var HtmlWebpackPlugin = require('html-webpack-plugin')
var webpackConfig = {
entry: 'index.js',
output: {
path: '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>
可以進行一系列的配置,支持如下的配置信息
- title: 用來生成頁面的 title 元素
- filename: 輸出的 HTML 文件名,默認是 index.html, 也可以直接配置帶有子目錄。
- template: 模板文件路徑,支持加載器,比如 html!./index.html
- inject: true | 'head' | 'body' | false ,注入所有的資源到特定的 template 或者 templateContent 中,如果設置為 true 或者 body,所有的 javascript 資源將被放置到 body 元素的底部,'head' 將放置到 head 元素中。
- favicon: 添加特定的 favicon 路徑到輸出的 HTML 文件中。
- minify: {} | false , 傳遞 html-minifier 選項給 minify 輸出
- hash: true | false, 如果為 true, 將添加一個唯一的 webpack 編譯 hash 到所有包含的腳本和 CSS 文件,對於解除 cache 很有用。
- cache: true | false,如果為 true, 這是默認值,僅僅在文件修改之后才會發布文件。
- showErrors: true | false, 如果為 true, 這是默認值,錯誤信息會寫入到 HTML 頁面中
- chunks: 允許只添加某些塊 (比如,僅僅 unit test 塊)
- chunksSortMode: 允許控制塊在添加到頁面之前的排序方式,支持的值:'none' | 'default' | {function}-default:'auto'
- excludeChunks: 允許跳過某些塊,(比如,跳過單元測試的塊)
下面的示例演示了如何使用這些配置。
{ entry: 'index.js', output: { path: 'dist', filename: 'index_bundle.js', hash: true }, plugins: [ new HtmlWebpackPlugin({ title: 'My App', filename: 'assets/admin.html' }) ] }
生成多個 HTML 文件
通過在配置文件中添加多次這個插件,來生成多個 HTML 文件。
{ entry: 'index.js', output: { path: 'dist', filename: 'index_bundle.js' }, plugins: [ new HtmlWebpackPlugin(), // Generates default index.html new HtmlWebpackPlugin({ // Also generate a test.html filename: 'test.html', template: 'src/assets/test.html' }) ] }
其中:webpack 插件: html-webpack-plugin https://www.cnblogs.com/grimm/p/5770829.html
html-webpack-plugin配置多頁面自定義模板 https://www.cnblogs.com/wonyun/p/6030090.html