Passing less variables from webpack

别说谁变了你拦得住时间么 提交于 2019-12-05 10:29:14

So it was tough but we finally made it work(!). Arggh - so much time invested to trying and figure out the syntax.

Here's the task: we want at build time to determine a path that should use used as the base url for misc assets in less files (background images, using url() less function).

First, we determined the path in webpack config file. Its plain JS, but the escaping pattern for the path string was absolutely nuts. We probably invested hours just on this. Amazing. Here it is:

var assetsPath = (someCondition) ? '/assets' : "\\/127.0.0.1:8080/assets";

Next is the loader configuration for less files, using the assetsPath prefix set above:

{
    test: /\.less$/,
    exclude: /node_modules/,
    loader: 'style!css?minimize=false!less?{"modifyVars":{"assetspath":"\'' + assetsPath +'\'"}}'
}

Notice the escaping pattern above where using the assetsPath in the loader configuration.

Next, you need to make sure that an empty variable is being defined in the less files. We initialized it in our 'vars.less' file, with:

@assetspath: '';

Finally, in any relevant class, we can use the value being passed in build time like this:

background-image: url("@{assetspath}/images/facebook.png");

You can try to use the query section of the loader:

    loader: 'style!css?-minimize!less?-minimize',
    query: {
        modifyVars: {
           "resources-path-prefix": pathPrefix
        } 
    }

It's a different approach to this situation, but we managed to make things work by converting into Base64 every resource that the CSS files loaded. We had to do this because figuring out the hostname of the resources was possible much later down the line than the webpack config file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!