Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing less variables from webpack

I'm trying to pass less variables within a webpack configuration to the less loader, naturally. For some reason the variable is not being passed ok. I can't figure the correct syntax.

The variable has a dynamic content that is determined at the build time, in the webpack config file. This is the relevant line (I've tried many variations of it):

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

In the above example some pathPrefix is being determined at build time and we want to pass its value into less context, where it will be used in url() css directives.

The above doesn't work - nothing is passed into less, and the default variable value defined in less applies.

Can anyone show how to correctly pass the value into the less compilation process? Thanks!

like image 237
Boaz Rymland Avatar asked Jul 13 '16 19:07

Boaz Rymland


2 Answers

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");
like image 181
Boaz Rymland Avatar answered Nov 15 '22 09:11

Boaz Rymland


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

    loader: 'style!css?-minimize!less?-minimize',
    query: {
        modifyVars: {
           "resources-path-prefix": pathPrefix
        } 
    }
like image 44
Naftali Avatar answered Nov 15 '22 11:11

Naftali