vue-cli3使用less全局變量,不用每個組件引入less文件(親測有效)


問題: 在global.less文件中定義一些全局使用的less變量;

結果組件使用這些全局變量時,都要@import "~@/styles/global.less"引入該文件,否則報錯

解決方法和步驟

1. 安裝style-resources-loader

yarn add style-resources-loader

2. 在vue.config.js中進行配置

module.exports = {
···

	// 引入全局樣式,這樣使用定義的less變量時,不用每次引入global.less了
    chainWebpack: config => {
        const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
        types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
    },

···

}

function addStyleResource(rule) {
	rule.use('style-resource')
		.loader('style-resources-loader')
		.options({
			patterns: [
				path.resolve(__dirname, './src/styles/global.less'), // 需要全局導入的less
			],
		})
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM