Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change import paths in webpack?

I have a set of exports that I normally import from one directory:

import { myThing } from 'path/to/dir/es5/things'

However, if I run webpack with a specific NODE_ENV set, I would like the root of all such imports to be treated as es6 instead:

import { myThing } from 'path/to/dir/es6/things'

How can I do this, e.g. have webpack dynamically resolve path/to/dir/es5/* to path/to/dir/es6/*?

like image 252
csvan Avatar asked Dec 22 '17 08:12

csvan


2 Answers

You can use an alias for that.

For example, in your webpack configuration, you can use something like:

const alias = {};
if (NODE_ENV === ...) {
    alias['path/to/dir/es5'] = 'path/to/dir/es6'
}

Further reading: https://webpack.js.org/configuration/resolve/

like image 138
Gilad Artzi Avatar answered Sep 19 '22 10:09

Gilad Artzi


Here is my way of handling this stuff.

Built-in DefinePlugin coupled with env variable.

in your package.json, add env variable in following way

"script": "... webpack --env.SOME_ENV_VAR=value -p"

Then, add your DefinePlugin inside your webpack.config file

plugins: [
    ...

    new webpack.DefinePlugin({
        SOME_ENV_VAR: env.SOME_ENV_VAR,
    }),

    ...
]

Then you can use SOME_ENV_VAR as global variable inside your code

/* global SOME_ENV_VAR */    

const esX = SOME_ENV_VAR === value ? 'es5' : 'es6';

myThing = require(`path/to/dir/${esX}/things`)
like image 36
Muhammet Enginar Avatar answered Sep 20 '22 10:09

Muhammet Enginar