我是靠谱客的博主 现实奇异果,这篇文章主要介绍webpack中的style-resources-loader加载全局css变量,现在分享给大家,希望可以做个参考。

我们在项目中经常会遇到这种场景,抽离了一些公用的样式,并且还会定义一些变量,比如:variables , mixins , function,之前都是在每个样式文件中手动的@import导入。style-resources-loader的作用就是避免重复在每个样式文件中@import导入,在各个css 文件中能够直接使用 变量和公共的样式。

例如我们抽离了这样一个scss文件作为公用的样式。
common.scss内容如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
$themeColor: #3472FC; //主题色 $hoverColor: #336be4; $activeColor: #234492; $em-base: 100; @mixin clearfix { &:after { content: ""; display: table; clear: both; } } @function strip-units($value) { @return ($value / ($value * 0 + 1)); } @function rem($pxval) { @if not unitless($pxval) { $pxval: strip-units($pxval); } $base: $em-base; @if not unitless($base) { $base: strip-units($base); } @return ($pxval / $base) * 1rem; } .disabled-img { width: 2.2rem; height: 2.2rem; background-size: 100%; position: fixed; bottom: 1.6rem; right: 0.5rem; z-index: 99; }

想要在项目中的其他样式文件用到common.scss里面的变量和样式,需要我们在vue.config.js中这样配置:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module.exports = { lintOnSave: false, // 是否开启eslint保存检测,有效值:ture | false | 'error' publicPath: publicPath, outputDir: path.resolve(__dirname, `./dist${publicPath}`), assetsDir: 'static', // assetsPublicPath: './', // 第三方插件配置 pluginOptions: { // 引入通用样式插件 'style-resources-loader': { preProcessor: 'scss', patterns: [ // __dirname获取当前文件完整路径名 path.resolve(__dirname, './src/css/mixin.scss') ] } }, }

上面是案例和webpack中的简单配置。下面来看一下style-resources-loader的具体安装和使用。

style-resources-loader安装方式有两种:

以less为例

方法1、先安装 css 预处理插件 less, less-loader, 然后安装 style-resources-loader , 再安装 vue-cli-plugin-style-resources-loader。vue 项目中需要 安装 这四个插件。

方法2、直接使用vue add style-resources-loader安装 ,会提示选择预处理器。如图:
在这里插入图片描述

在 vue-cli中的配置

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = { pluginOptions: { 'style-resources-loader': { preProcessor: 'less', patterns: [ // 这个是绝对路径,不能使用 alias中配置的别名路径,如@表示的src path.resolve(__dirname, './src/style/params.less') ] } }, …… 其他配置 …… }

在普通webpack 中的配置, 可以同时使用 多个预处理器

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = { // ... module: { rules: [{ test: /.less$/, use: ['style-loader', 'less-loader', 'less-loader', { loader: 'style-resources-loader', options: { patterns: [ // 只有一条时也可以写成对象形式 path.resolve(__dirname, 'path/to/scss/variables/*.less'), path.resolve(__dirname, 'path/to/scss/mixins/*.less'), ], injector: 'append' // 如果在样式文件之后导入就加此行配置 } }] }] }, // ... }

options选项的参数

  1. patterns:字符串或数组,表示导入资源的路径,必须是绝对路径
  2. injector:‘prepend’ 或者 ‘append’, 表示资源导入的位置,在之前还是之后,样式后导入的会覆盖前面导入的
  3. resolveUrl: 是否允许@import形式导入,默认true

参考了下面两篇文章,非常感谢
https://www.jianshu.com/p/13d9f18faafe
https://blog.csdn.net/qq_40999917/article/details/107612686

最后

以上就是现实奇异果最近收集整理的关于webpack中的style-resources-loader加载全局css变量的全部内容,更多相关webpack中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部