vue3中less一次导入全局使用的解决方案

359 阅读1分钟

题引:

最近在做一个新的项目,期间用到了 less 作为样式文件。但是发现在main.js中引入的文件并没有全局使用,在每一个组件里面都需要重新导入,这就比较繁琐了,而且引用越多导致性能越差。因此通过查找和尝试,终于找到一种方法。

方案:

使用 style-resources-loader 插件进行全局使用。只需要简单几步即可完成全局使用

  1. 下载style-resources-loader

    npm install style-resources-loader / pnpm add style-resources-loader;

  2. 配置vue.config.js

    const {defineConfig} = require('@vue/cli-service')
    const path = require('path');
    
    function resolve(dir) {
        return path.join(__dirname, '', dir)
    }
    
    module.exports = defineConfig({
        ....
        chainWebpack:config=>{
            config.module.rule('style-resources')
                .test(/\.less$/).use('style-resources')
                .loader('style-resources-loader)
                .options({
                    patterns:[{
                        path:resolve(__dirname,'./src/assets/css/index.less');//放自己的less路径
                    }]
                })
        }
    })
    

通过上面的配置,即只需在main.js文件中导入less文件,那么全部的组件都可共享less。