使用plugin
#1 通过npm安装相应的plugin
#2 在webpack.config.js的plugins中配置插件
BannerPlugin
//webpack.config.js
const webpack = require('webpack')
module.exports = {
...
plugins:[
new webpack.BannerPlugin("最终版权归***所有")
]
}
html-webpack-plugin
项目发布时使用的是dist文件夹下的内容,但index.html在根目录下的话,dist文件夹下的已经被打包过的js文件等也就失去意义了,为了将index.html也打包进dist,需要使用htmlWebpackPlugin插件
。
htmlWebpackPlugin插件
能够自动生成一个index.html文件,并将打包过的js文件自动添加到index.html文件的<body>
中。
npm install html-webpack-plugin --save-dev
const htmlWebpackPlugin= require('html-webpack-plugin')
plugins:[
new webpack.BannerPlugin("最终版权归***所有"),
new htmlWebpackPlugin({
template:'index.html' //根据什么模板来生成index.html
})
]
uglifyjs-webpack-plugin
该插件用于对打包的js文件进行压缩。
npm install uglifyjs-webpack-plugin@1.1.1 --save-dev //这里指定1.1.1版本,与CLI2保持一致
const uglifyjsPlugin = require('uglifyjs-webpack-plugin')
plugins:[
new uglifyjsPlugin()
]
webpack搭建本地服务器
webpack提供了一个可选的本地开发服务器,该服务器基于node.js搭建,内部使用express框架。
因为它是一个单独的模块,在使用之前需要安装:
npm install --save-dev webpack-dev-server@2.9.1
//webpack.config.js
module.exports = {
...
devServer:{
contentBase:'./dist', //为哪一个文件夹提供本地服务,默认是根文件夹
inline:true //页面是否实时刷新
//其它可选参数
//port 端口号,默认8080
//historyApiFallback 在SPA页面中,依赖HTML5的history模式
}
}
之后在package.json中配置scripts:
"scripts":{
...
"dev":"webpack-dev-server" //webpack-dev-server --open会自动打开服务器
}
webpack配置的分离
将webpack配置分离为开发时依赖与运行时依赖,使逻辑更清晰。
创建三个js文件:base.config.js(仅保存公共配置)、prod.config.js(仅保存生产依赖的配置)、dev.config.js(仅保存运行依赖的配置)。
npm install --save-dev webpack-merge
//prod.config.js
const webpackMerge = require('webpack-merge')
const baseConfig = require('./base.config.js')
module.exports = webpackMerge(baseConfig,{
plugins:[
...
],
...
})
之后还需要修改package.json的scripts属性,因为配置文件已经不再是webpack.config.js,不指定新的配置路径webpack会找不到配置文件。
//package.json
"scripts":{
...
"build":"webpack --config ./build/prod.config.js",
"dev":"webpack-dev-server --open --config ./build/dev.config.js"
}
//注意,如果配置文件不再根目录下,可能需要修改output的path参数,否则bundle.js可能不在希望的文件夹内