3

I'm looking for a solution to dynamically import modules in JS react components based on parameters from a webpack configuration.

So that THEME_PATH from import ./theme/{THEME_NAME}/indes.less

Would be dynamically replaced through a webpack param or CLI parameters on webpack build.

Any suggestions or hints on how to solve this?

rnevius
  • 26,578
  • 10
  • 58
  • 86
Dilemmat_Dag
  • 383
  • 1
  • 4
  • 14

1 Answers1

4

It is possible with DefinePlugin:

webpack config:

   plugins: [
        ...
        new webpack.DefinePlugin({
            __THEME__: '"' + process.env.THEME.toString() + '"'
        })
    ]

and in your code:

require('./theme/' + __THEME__ + '/index.less')

You can pass THEME in this way (depends on your OS and shell).

Also you can pass prameters from cli instead of using process.env.


If you importing theme in less file, not js:

less file:

@import "theme/@{THEME}/index.less";

webpack config (less-loader):

'!less?{"modifyVars":{"THEME":"' + process.env.THEME + '"}}'
Community
  • 1
  • 1
Bob Sponge
  • 4,708
  • 1
  • 23
  • 25
  • 1
    Great. This solved my problem. An additional note to this is that require('./theme/' + __THEME__ + '/index.less') works fine but import '../theme/' + __THEME__ + '/index.less' will fail – Dilemmat_Dag Apr 13 '16 at 08:49
  • Thanks! Is it possible also with `import` syntax? I'm using `import` everywhere and would have to use `require` just in a single place. – szimek Dec 21 '16 at 17:13
  • You cant use `import` with variables, so it is not possible. – Bob Sponge Dec 22 '16 at 06:33