目录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不少,建议碰到有相应需求再去学习对应的插件,教程后续还会陆续用到一些其它的插件