平时在项目开发中,我们常常有一些类似的样式设置可以封装成mixin方法,实现复用。比如设置背景图,我们希望有一个方法,我们给它传入背景图地址,它帮我们设置好背景图大小位置等。并且这样的方法我们常常需要在多个页面用到,难道我们就只能在所有要用到的页面中都引入包含这个方法的文件吗?
这里我们将mixin方法放在mixin.less文件中。
对于这个问题,我最开始想的是,在入口文件index.js引入mixin.less文件,应该就可以实现全局都可以用这个方法了吧? 然而实践告诉我并不能,可以看到,mixin方法并没有被预编译出来,并不能使用。
携带参数的 mixin 在编译的时候不会输出本身。它的属性将输出在调用它的模块中。
所以上面的方法不好使,另一种方法是利用webpack打包构建工具。
- 首先安装style-resources-loader
npm install style-resources-loader
或者用yarn
yarn add style-resources-loader
- 修改配置文件(注意根据自己的文件地址修改对应的less文件地址)
// 全局注入mixin.less
const path = require("path")
function addStyleResource (rule) {
rule.use('style-resource')
.loader('style-resources-loader')
.options({
patterns: [
path.resolve(__dirname, './src/assets/less/mixin.less'),
],
})
}
module.exports = {
chainWebpack(config) {
const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
}
}
- 重新启动项目
- 验证是否有效
不通过@import引入mixin文件,然后再页面中使用文件中的mixin方法看是否生效。