親測在vue 3.x中自動引入全局less變量

vue項目開發過程中,每次都引入一次全局變量覺得很麻煩,接下來就可以解決你的麻煩了.

首先我們要用到一個工具 style-resources-loader

執行這個命令安裝.

npm i style-resources-loader --save-dev

然後在vue.config.js中配置

const path = require('path');
/**
 * 自動引入全局的less變量
 * @param {*} rule
 */
const addStyleResource = (rule) => {
    rule.use('style-resource')
        .loader('style-resources-loader')
        .options({
            patterns: [
                // 需要全局導入的less,這個地方一點要寫./src纔行,否則會報錯...
                path.resolve(__dirname, './src/assets/styles/constant.less') 
            ]
        });
};
module.exports = {
    chainWebpack: (config) => {
        const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];
        types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)));
    },
    css: {
        loaderOptions: {
            less: {
                javascriptEnabled: true
            }
        }
    }
};

原文: https://cli.vuejs.org/zh/guide/css.html#%E9%A2%84%E5%A4%84%E7%90%86%E5%99%A8

最後,配置完成後需要重啓一下項目.重新npm start 即可.

然後就可以在項目中直接使用全局的less變量了

寫在後面,目前看了一下網上還有別的方法,

方法一 (測試了,反正我這裏用不了.別的未知)

 方法二(測試了,我這裏還是用不了.別的未知)

真是讓人頭凸 ┭┮﹏┭┮ 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章