您的位置:首页 > Web前端 > Webpack

Webpack 3.x 创建多个template及rimraf使用

2017-11-25 18:02 274 查看
如果是使用的webpack-dev-server模式的话,它是从内存中去读取目标模板的,也就是说如果现在磁盘上的index.html被删除了,对它读取index.html没有任何影响,那么现在我要做这样的件事,将目标模板index.html更换一下目录位置,也就是说这种情况会是在使用webpack -d的模式下才有意义,所以现在就切换回这种模式:

"scripts": {
"dev": "webpack -d --watch",
"prot": "webpack -p"
}


而它之前的存放的目录是:

output:{
path: __dirname + "/dist",
filename: "app.bundle.js"
}


更改模板文件的目录只需要在HtmlWebpackPlugin中添加一个filename字段:

new HtmlWebpackPlugin({
title: 'webpack',
filename: './../index.html', // 表示在root目录下
hash: true,
template: './src/my-index.html', // Load a custom template (lodash by default see the FAQ for details)
})


那么这个时候生成的模板中的其他的引入的JS、CSS文件的路径会不会受影响呢,其实是不会的:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>webpack</title>
<link href="dist/styles.css?ab4b7ed4485fa7430abe" rel="stylesheet"></head>
<body>
<div id="root"></div>
<!-- <p>hello react</p> -->
<script type="text/javascript" src="dist/app.bundle.js?ab4b7ed4485fa7430abe"></script></body>
</html>


可以看到JS/CSS的路径也是作了相对应的改变的。

现在要做的事情是这样,项目中肯定会需要多个模板,每个模板中会有相对应的JS/CSS,这个时候怎么做呢?

另一个模板:anotherPage.html 它所对应的JS是anotherPage.js,在src目录下,只在控制台输出一句话:

console.log("this is from anther template");


当有多个模板的时候,就意味着必须有多个entry:

entry: {
app: "./src/app.js",
anotherPage: "./src/anotherPage.js"
},
output:{
path: __dirname + "/dist",
filename: "[name].bundle.js" //name对应上面的两个entry
}


然后再更改plugins里的htmlWebpackPlugin:

new HtmlWebpackPlugin({
title: 'app template',
excludeChunks:['anotherPage'],//不要包含anotherPage的JS/CSS等
hash: true,
template: './src/my-index.html', // Load a custom template (lodash by default see the FAQ for details)
}),
new HtmlWebpackPlugin({
title: 'anotherPage template',
hash: true,
chunks: ['anotherPage'],//只包含anotherPage的JS
filename: 'anotherPage.html',//生成的文件会在dist目录下
template: './src/anotherPage.html', // Load a custom template (lodash by default see the FAQ for details)
}),


重新build之后,this is homepage(index.html) 可以看到它有相应的CSS样式,并且它的console中没有任何的输出(ignore errors first),因为app.js中并没有console.log(…) :



而在anotherPage.html中,可以看到它并没有红色的背景,因为它使用的JS是anotherPage.js,在这个js中并没有添加任何的sass,所以它没有背景样式,并且在console中有输出『this is from another template』:



在production 环境中可能在每次build 的时候想把dist目录下的所有旧的文件全部删掉,因为每次build的时候都会再生成相对应的file,可以使用rimraf命令:

npm i -D rimraf


安装完成后,在package.json中它的当前版本是:

"rimraf": "^2.6.2",


然后同样,在scripts对象中添加一个新的clean 命令,并把production 的命令也作相应的更改:

"scripts": {
"dev": "webpack-dev-server",
"prot": "npm run clean && webpack -p",
"clean":"rimraf ./dist/*"
},


然后运行命令:

npm run prot


这样就可以达到预期目的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webpack