首页 > 其他分享 > webpack 插件应用

webpack 插件应用

时间:2023-02-11 21:33:38浏览次数:39  
标签:index 插件 dist 文件 js webpack html 应用

plugin

1. clean-webpack-plugin

  • 介绍

主要用来清除文件,默认webpack打包后dist文件下的js文件是不会自动清除的,修改之后再次打包旧的文件会仍然存在

  • 安装
npm install --save-dev clean-webpack-plugin
  • 引用
//webpack.config.js中添加CleanWebpackPlugin插件
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin(
['dist/main.*.js','dist/manifest.*.js',],  //匹配删除的文件
['dist']//删除整个dist

)
]
}

2. html-webpack-plugin

  • 介绍
|- /dist //用于放打包后文件的文件夹
|- bundle.js //出口文件
|- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
|- index.js //入口文件
|- package.json
|- webpack.config.js //webpack配置文件

如果在只有index.js一个入口文件,只需要在index.html直接手动引用出口文件

<script src="bundle.js"></script> <!--这是手动引用的bundle.js-->

如果多个入口文件就需要手动添加不同的出口文件会很麻烦。而html-webpack-plugin插件可以使用模板生成html,整个文件会自动引用出口文件。

  • index.js
import _ from 'lodash';
import printMe from './print.js';

function () {
}
  • webapck.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: {
app: './src/index.js', //多个入口文件
print: './src/print.js'
},
plugins: [ //webpack 通过 plugins 实现各种功能, 比如 html-webpack-plugin 使用模版生成 html 文件
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Test Index ',
template: './src/index.html',
filename: 'index.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
chunks: ['index'],//生成的html就只会载入自身需要的bundle.js
}),
new HtmlWebpackPlugin({
title: 'Test Print',
template: './src/index.html',
filename: 'print.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
chunks: ['print']//生成的html就只会载入自身需要的bundle.js
})
],
output: {
filename: '[name].bundle.js', //根据入口文件输出不同出口文件
path: path.resolve(__dirname, 'dist')
}
};
  • 打包后的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript" src="app.bundle.js"></script>
<script type="text/javascript" src="print.bundle.js"></script></body>
</html>
  • 提取公共模块
    在index.js 和 print.js中引入公共模块,比如 公共样式、封装的api
    可以将这些公共的模块提取出来,在webpack.config.js中的optimization添加一个splitChunks进行配置。
optimization: {
splitChunks: {
// 自动提取所有公共模块到单独 bundle
chunks: 'all'
}
},

打包后就会生成一个入口公共的模块index~print.bundle.js

标签:index,插件,dist,文件,js,webpack,html,应用
From: https://blog.51cto.com/u_15885506/6050980

相关文章