1. Vue.config.js 中自定义ChainWebPack配置解析less
Tip(背景): 自定义ChainWebPack相关配置用以编译less文件。
1.1 修改babel配置文件style属性
babel.config.js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
"plugins": [
// `style: true` 会加载 less 文件
["import", { "libraryName": "ant-design-vue", "libraryDirectory": "es", "style": true }]
]
}
1.2 vue.config.js中配置chainWebpack属性
Tip:VUE CLI中默认存在less编译处理规则
这里为了验证自定义less相关配置,需要删除默认的less配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
//打印日志:true 默认规则中存在less文件编译配置
console.log(config.module.rules.has('less'));
// 删除less编译配置
config.module.rules.delete('less');
//打印日志: false 默认规则中存在less文件编译配置
console.log(config.module.rules.has('less'));
config.module
// 判断是否存在less-to-css规则
.rule('less-to-css')
// rule对象的test属性设置,返回rule对象
.test(/\.less$/)
// rule对象的use属性设置,返回Use<this>对象
.use('style-loader')
// 如果要设置多个loader的话,需要设置不同的name,在map中,如果name相同,则会覆盖之前的值
.loader('style-loader')
// 返回父类,这里返回的Rule对象
.end()
.use('css-loader')
.loader('css-loader')
.end()
.use('less-loader')
// 设置Use对象的loader属性,返回Use<this>对象
.loader('less-loader')
// 将上面的Use<this> 对象放到css-loader对象的后面
.options({
lessOptions: {
webpackImporter: true,
// 必须设置。
javascriptEnabled: true
}
})
.end();
//打印日志: false 默认规则中存在less文件编译配置
console.log(config.module.rules.has('less-123'));
}
})
1.3 执行配置预览命令,预览webpack配置文件。
- package.js文件中设置inspect命令
- 执行命令输出webpack.config.js文件
PS D:\code\vue-demo\vue-20220625> npm run inspect > webpack.config.js
Debugger attached.
Debugger attached.
Waiting for the debugger to disconnect...
Waiting for the debugger to disconnect...
PS D:\code\vue-demo\vue-20220625>
- 查看webpack.config.js文件
1.4 启动工程,验证是否OK
npm run serve
FAQ:
问题1:模块转换失败,@无法解析?
ERROR in ./node_modules/ant-design-vue/es/tooltip/style/index.less 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> @root-entry-name: default;
|
| @import './index-pure.less';
@ ./node_modules/ant-design-vue/es/tooltip/style/index.js 2:0-22
@ ./node_modules/ant-design-vue/es/menu/style/index.js 5:0-29
@ ./node_modules/babel-loader/lib/index.js??clonedRuleSet-35.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/App.vue?vue&type=script&lang=js 3:0-38
@ ./src/App.vue?vue&type=script&lang=js 1:0-189 1:0-189 1:190-368 1:190-368
@ ./src/App.vue 2:0-54 3:0-49 3:0-49 8:49-55
@ ./src/main.js 2:0-28 3:10-13
原因:less文件中@无法解析
- less版本不匹配
- less-loader无法加载编译less文件,webpack中less-loader配置有误
解决办法:
{
test: /\.less$/,
use: [
/* config.module.rule('less-to-css').use('style-loader') */
{
loader: 'style-loader'
},
/* config.module.rule('less-to-css').use('css-loader') */
{
loader: 'css-loader'
},
/* config.module.rule('less-to-css').use('less-loader') */
{
loader: 'less-loader',
options: {
lessOptions: {
webpackImporter: true,
javascriptEnabled: true
}
}
}
]
}