Boaz Rymland Boaz Rymland - 3 years ago 305
Less Question

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!

Answer Source

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' : "\\/";

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download