在less-loader中导入全局变量 [英] Import global variables in less-loader

查看:91
本文介绍了在less-loader中导入全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 webpack 配置中,我希望能够定义一个全局的 less-variables 文件,该文件将包含在每个 less 组件中.

In my webpack config, I want to be able to define a global less-variables file which would be included in every less component.

使用 sass-loader,您可以提供以下选项:

With the sass-loader you can supply the following option:

loaderOptions: {
    data: "@import 'globals.sass'"
}

我能用 less-loader 找到的唯一选项是 globalVars:

The only option I could find with the less-loader is globalVars:

loaderOptions: {
    globalVars: {}
}

现在,这一切正常,但是 globalVars 需要一个带有键值对的对象.我宁愿在每个组件都附加一个 theme.less .使用 less-loader 可以做到这一点吗?

Now, this works all right, but globalVars expects an object with key-value pair. I'd rather have a theme.less somewhere which is appended with every component. Is this possible with the less-loader?

推荐答案

我建议将您的 less-loadertext-transform-loader 链接起来,如下所示:

I suggest chaining your less-loader with the text-transform-loader, like this:

rules: [{
     test: /\.js$/,
     use: [
         { 
            loader: 'less-loader',
            options: //your normal options
         },
         { 
            loader: 'text-transform-loader',
            options: {
               prependText: '@import "../styles/theme.less"'
            }
         }
     ]
}]

请记住,最后一个 webpack loader 是最先应用的,因此您可能希望将它用作链中的最后一个 loader.如果您的 less 文件嵌套在不同的深度,这很可能会中断,因为这样您的主题文件相对于每个文件将处于不同的深度.如果是这种情况,您可以将主题文件的全部内容附加到每个 less 文件中!

Remember that the last webpack loader is applied first, so you probably want to use this one as the last loader in your chain. This may well break if your less files are nested at different depths, because then your theme file will be at different depths relative to each one. If that's the case, you could just append the entire content of the theme file to each less file!

从这个规则中排除你的 theme.less 文件也是一个好主意,否则你会得到一些奇怪的无限递归.

Would also be a good idea to exclude your theme.less file from this rule, otherwise you could get some weird infinite recursion.

参见 https://github.com/kmck/webpack-text-transform-加载器了解详情.

这篇关于在less-loader中导入全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆