vue工程为组件自动注入全局样式文件,用 CSS 插件自动注入全局变量样式

开发过程中,随着工程变大,不免要提取出一些公共的样式,如variables、mixins、functions等几乎在所有业务组件中都会用到的样式:
在这里插入图片描述
如果每个需要的组件都要手动导入一次,就太繁琐了:

<script lang="less">
@import "../styles/variables";
@import "../styles/mixins";
@import "../styles/functions";
// 其他样式
</script>

当然最直接的改进方案是创建一个包含上面引入的入口样式文件entry.less,然后在各组件中导入即可:

// entry.less
@import './variables';
@import './mixins';
@import './functions';
<script lang="less">
@import "../styles/entry";
// 其他样式
</script>

但是高端的猎人,用上述的方法还是会比较繁琐,而是借助webpack等工具,完成全局的自动注入。

Less和Stylus

配置Less和Stylus自动导入有两种方案

  1. 使用style-resources-loader (https://github.com/yenshih/style-resources-loader)
  2. 使用vue-cli-plugin-style-resources-loader(https://www.npmjs.com/package/vue-cli-plugin-style-resources-loader)

这里我们推荐使用第一种,因为第二种方案只是对第一种方案的包装,且暂不支持热更新

安装style-resources-loader

$ npm i -D style-resources-loader

配置vue.config.js

// vue.config.js
const path = require('path')
module.exports = {
    
    
  chainWebpack: config => {
    
    
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))  // A
  },
}
function addStyleResource (rule) {
    
    
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
    
    
      patterns: [
        path.resolve(__dirname, './src/styles/entry.less'),  // B
      ],
    })
}
// 如果想要配置多个导入,只需在B行后继续添加即可:
patterns: [
  path.resolve(__dirname, './src/styles/entry1.less'),
  path.resolve(__dirname, './src/styles/entry2.less'),
],

Sass/Scss
其实Sass/Scss配置自动导入也可以使用上面的方案,但是使用其原生的方案更加便捷,只需在vue.config.js中配置即可:

// vue.config.js
module.exports = {
    
    
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        prependData: `@import "@/styles/entry.scss";`  // A
      }
    }
  }
}
// 如果想要配置多个导入,只需在A行继续添加即可:
// vue.config.js
module.exports = {
    
    
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        prependData: `
            @import "@/styles/entry1.scss";
            @import "@/styles/entry2.scss";
        `
      }
    }
  }
}
注意:[email protected]之前,要将上面的prependData替换为data。
注意: 在 sass-loader v8 中,这个选项是 prependData
v8之后是additionalData 例如:  additionalData: `@import "@/style/theme/index.scss";`,

猜你喜欢

转载自blog.csdn.net/weixin_43131046/article/details/125015419
今日推荐