vue.config.js
官网:https://cli.vuejs.org/zh/config/#vue-config-js
PublicPath
部署应用包时的基本 URL。用法和 webpack 本身的 output.publicPath 一致,
默认值为 ‘/’ , Vue CLI 会假设你的应用是被部署在一个域名的根路径上 https://abc.com/
可以设置为子路径 - 如果你的应用被部署在 https://abc.com/sub/ 那么就设置为 ‘/sub’
可以设置为 CDN 路径 - 在我们的应用中,最后静态资源是要全部上传到 CDN 的,(脚手架自动完成),所以这里可以设置为一个 CDN 域名 - ‘https://oss.imooc-lego.com/editor’
还可以设置为相对路径(’’ 或者 ‘./’),这样所有的资源都会被链接为相对路径
css.loaderOptions
官网:https://cli.vuejs.org/zh/config/#css-loaderoptions
插件
webpack-bundle-analyzer
webpack-bundle-analyzer是打包分析工具
可以作为 webpack plugins 使用
可以作为 cli 命令行工具使用
作用:
分析 Bundle 由什么模块组成
分析什么模块占据了比较大的体积
分析是否有什么错误的模块被打包了
根据图表的优化步骤:
1、看是否有重复的模块,或者没有用的模块被打包进代码中
1、看package.json,是否有应该在devDependencies中的模块,被错误的放到了dependencies中
2、看是否有重复的模块,将其删除
3、是否有没有用的模块被打包进代码中 使用webpack ignore plugin去除
配置
const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = defineConfig({
transpileDependencies: true,
// 公共路径(必须有的)
publicPath: "./",
// 输出文件目录
outputDir: "dist",
// 静态资源存放的文件夹(相对于ouputDir)
assetsDir: "assets",
productionSourceMap: true, // 不需要生产环境的设置false可以减小dist文件大小,加速构建
css: {
loaderOptions: {
sass: {
// 全局引入变量和 mixin 引入的样式可以直接在组件里使用
// 7.x版本的param是data
// 8.x版本的param是prependData
// 9.x版本的param是additionalData
additionalData: `
@import "@/assets/scss/variable.scss";
@import "@/assets/scss/mixin.scss";
`
}
}
},
devServer: {
proxy: {
'/api': {
target: 'http://192.168.3.30:8092/', // 代理跳转的地址
pathRewrite: { '^/api': '' },
changeOrigin: true,
secure: false // 接受 运行在 https 上的服务
}
}
},
chainWebpack: (config) => {
// 这是为了剔除没有使用但被打包进去的模块
// 这块写法不一定对,没有测试
config.plugin('ignore')
.use(new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}))
config.plugin('context')
.use(webpack.ContextReplacementPlugin,
[/moment[/\\]locale$/, /zh-cn/])
config.plugin('html')
.tap(args => {
args[0].title= 'vue移动端开源项目'
return args
})
config.plugin('webpack-bundle-analyzer')
.use(BundleAnalyzerPlugin)
// 分割第三方组件库
config.optimization.splitChunks = {
maxInitialRequests: Infinity,
minSize: 300 * 1024,
chunks: 'all',
cacheGroups: {
antVendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name.
// node_modules/packageName/sub/path
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
return `npm.${packageName.replace('@', '')}`
}
},
}
}
}
})
说明
1、可以通过执行vue inspect > output.js命令,生成output.js文件,来查看vue-cli对webpack插件的抽象
vue.config.js文件里这样修改
chainWebpack: (config) => {
// 修改HtmlWebpackPlugin插件的配置
config.plugin('html')
.tap(args => {
args[0].title= 'vue移动端开源项目'
return args
})
}
index.html里使用
<title><%= htmlWebpackPlugin.options.title %></title>
通过options.title获取上面配置的值
如果想增加其他值,可以在args[0].title下面添加