一步步教你利用webpack如何搭一个vue脚手架(超详细讲解和注释)

2020-06-16 05:54:29易采站长站整理

//作用域提升,提升代码在浏览器执行速度
new webpack.optimize.ModuleConcatenationPlugin(),
//抽离公共模块,合成一个chunk,在最开始加载一次,便缓存使用,用于提升速度!
// 1. 第三方库chunk
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: function(module) {
//在node_modules的js文件!
return (
module.resource &&
/.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, "../node_modules")) === 0
);
}
}),
// 2. 缓存chunk
new webpack.optimize.CommonsChunkPlugin({
name: "manifest",
minChunks: Infinity
}),
// 3.异步 公共chunk
new webpack.optimize.CommonsChunkPlugin({
name: "app",
children: true,
// (选择所有被选 chunks 的子 chunks)
async: true,
// (创建一个异步 公共chunk)
minChunks: 3
// (在提取之前需要至少三个子 chunk 共享这个模块)
}),
//将整个文件复制到构建输出指定目录下
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, "../static"),
to: prodConfig.staticPath,
ignore: [".*"] }
]),
//生成html
new HtmlWebpackPlugin({
filename: path.resolve(__dirname, "../public/index.html"),
template: "index.html",
favicon: path.resolve(__dirname, "../favicon.ico"),
//js资源插入位置,true表示插入到body元素底部
inject: true,
//压缩配置
minify: {
//删除Html注释
removeComments: true,
//去除空格
collapseWhitespace: true,
//去除属性引号
removeAttributeQuotes: true
},
//根据依赖引入chunk
chunksSortMode: "dependency"
})
]});
module.exports = prodConf;

十. 创建 build/build.js

10.1 此文件是项目打包服务,用来构建一个全量压缩包

10.2


"use strict";
//node for loading
const ora = require("ora");
// rm-rf for node
const rm = require("rimraf");
//console for node
const chalk = require("chalk");
//path for node
const path = require("path");
//webpack
const webpack = require("webpack");
//webpack production setting
const config = require("./webpack.prod.conf");
//指定删除的文件
const rmFile = path.resolve(__dirname, "../public/static");
//build start loading
const spinner = ora("building for production...");
spinner.start();
//构建全量压缩包!
rm(rmFile, function(err) {
if (err) throw err;
webpack(config, function(err, stats) {
spinner.stop();
if (err) throw err;
process.stdout.write(
stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + "nn"
);
if (stats.hasErrors()) {
console.log(chalk.red(" Build failed with errors.n"));