目錄html
上節:entry與outputwebpack
先整理目錄,把src/main.js, bundles刪除,刪完後目錄以下:
webpack.config.js:web
const { resolve } = require('path'); module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].[contenthash:8].js', path: resolve(__dirname, 'bundles') } };
先執行下打包:npm run build, 生成bundle文件夾:npm
如今有兩個問題:segmentfault
爲了解決上述問題,介紹本教程使用的第一個插件:瀏覽器
安裝plugin:app
npm i html-webpack-plugin -D
修改配置:
webpack.config.js學習
const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].[contenthash:8].js', path: resolve(__dirname, 'bundles') }, plugins: [new HtmlWebpackPlugin()] };
而後:npm run build, 打包後以下:測試
打開bundles/index.html:ui
利用html-webpack-plugin,每次打包後都會新生成一個html文件,並自動引入相應依賴
html-webpack-plugin經常使用配置:
webpack.config.js:
// ... plugins: [ new HtmlWebpackPlugin({ // 設置模板title title: 'use HtmlWebpackPlugin', // 生成的模板名稱,默認 'index.html', 規則相似output filename: 'admin.html', // 指定生成的html文件依賴的模板 template: './index.html', // 生成favicon favicon: 'path/to/example.ico', // 插入meta標籤 meta: { 'viewport': 'width=device-width, initial-scale=1, shrink-to-fit=no user-scalable=no', 'apple-touch-fullscreen': 'yes', } // .... }) ] // ...
參考:https://webpack.js.org/plugin...
每次打包時,bundles目錄都是直接更新,咱們但願每次打包能夠先刪後增。
clean-webpack-plugin便能實現這個需求
安裝
npm i clean-webpack-plugin -D
webpack.config.js:
const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].[contenthash:8].js', path: resolve(__dirname, 'bundles') }, plugins: [ new HtmlWebpackPlugin(), new CleanWebpackPlugin() ] };
測試:再bundles下隨便新建個文件,好比
而後npm run build: 那個新建的test.txt就沒了
總結:webpack的plugin不少,建議碰到有相應需求再去學習對應的插件,教程後續還會陸續用到一些其它的插件