一、前言
有一vue项目,需要修改css和js文件打包后的输出路径。因为不熟悉vue-cli打包配置项,在网上搜索了一波,没有比较好的解决方案
二、问题描述
1、js 输出路径配置,没什么问题
module.exports = {
configureWebpack: (config) => {
return {
output: {
filename: 'm-js/[name].js',
chunkFilename: 'm-js/[name].js',
},
}
},
}
2、css 输出路径配置(有问题版本)
module.exports = {
configureWebpack: (config) => {
return {
plugins: [
new MiniCssExtractPlugin({
// 修改打包后css文件名
filename: 'm-css/[name].css',
chunkFilename:'m-css/[name].css',
})
]
}
}
}
这样配置后,打包出来是这样的,之前的css文件目录依然存在。感觉像是vue-cli 内置的配置和我们的配置同时起作用了。
三、寻找答案
然后就去看vue-cli 默认的webpack 配置,发现使用的是 ExtractTextPlugin插件,
// cli默认配置 webpack.prod.conf.js文件
plugins: [
// 此处省略
// http://vuejs.github.io/vue-loader/en/workflow/production.html
// extract css into its own file
// 翻译 抽取css到文件中
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
// 此处省略
]
通过查阅 vue-cli 文档 得知以下配置
css.extract#
-
Type:
boolean | Object -
Default: 生产环境下是
true,开发环境下是false是否将组件中的 CSS 提取至一个独立的 CSS 文件中 (而不是动态注入到 JavaScript 中的 inline 代码)。
同样当构建 Web Components 组件时它总是会被禁用 (样式是 inline 的并注入到了 shadowRoot 中)。
当作为一个库构建时,你也可以将其设置为
false免得用户自己导入 CSS。提取 CSS 在开发环境模式下是默认不开启的,因为它和 CSS 热重载不兼容。然而,你仍然可以将这个值显性地设置为
true在所有情况下都强制提取。
但是并没有说 extract是对象时该怎样传参,大胆猜一下,既然是负责css 提取,那么这些参数应该是传给 ExtractTextPlugin 的,改为以下配置(仅截取了有用部分):
module.exports = {
publicPath: './',
lintOnSave: true,
css: {
// 若为false则不抽离,放在内联style中
// 默认为true
extract: {
filename: 'm-css/[name].[hash:8].css',
chunkFilename: 'm-css/[name].[hash:8].css'
},
},
configureWebpack: (config) => {
return {
output: {
filename: 'm-js/[name].js',
chunkFilename: 'm-js/[name].js',
},
}
},
}
build之后