持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情
webpack有什么不足的地方呢?
webpack打包后的出口文件里,会做一些兼容,所以会有好多冗余的代码。
原入口文件里面用的是export引入文件,打包后就会用webpack自己的方法,webapck_require,webpack所有导出导入都做了处理,这就是webpack的启动函数主要做兼容,所以代码会比较冗余;比如:2行代码,最后打包出来的代码可能会有100行,所以就出现了其他的一些库,出来的代码比较干净。
Plugins
webpack的补充扩展,对输出目录(打包目录)有想法有配置的,可以考虑用这个。
作用于webpack打包的整个过程,webpack的打包过程是有(生命周期概念)钩子。
plugin可以在webpack运行到某个阶段的时候,帮你做一些事情,类似于生命周期的概念,扩展插件,在Webpack构建流程中的特定时机注入扩展逻辑改变构建结果或做你想要的事情,作用于整个构建过程。
HtmlWebpackPlugin
htmlWebpackPlugin会在打包结束后,自动生成一个html文件,并把打包生成的js模块引入到该html中。
npm install --save-dev html-webpack-plugin
配置:
title: 用来生成页面的title元素。
filname: 输出文件的html文件名,默认是 index.html,也可以直接配置带有子目录。
temple: 模板文件路径,支持加载器,比如: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: 允许跳过某些块,(⽐如,跳过单元测试的块)
eg:
webpack.config,js:
const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
...
plugins: [
new htmlWebpackPlugin({
title: "My App",
filename: "app.html",
template: "./src/index.html"
})
]
};
index.html:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
clean-webpack-plugin
npm install --save-dev clean-webpack-plugin
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
...
plugins: [
new CleanWebpackPlugin()
]
clean-webpack-plugin:如何做到dist目录下某个某个文件或者目录不被清空:使用配置项:cleanOnceBeforeByildPatterns。
案例:cleanOnceBeforeBuildPatterns: ["/*", "!dll", "!dll/"], !感叹号相当于exclude排除,意思是清空操作排除dll目录,和dll目录下多有文件。注意:数组列表里的 “*/”是默认值,不可忽略,否则不做清空操作。