Include paths for imports in babel using webpack

2.8k Views Asked by At

Given a directory structure such as:

project
├───common
│   └───js
└───src
    └───js

is there any way to add import paths to webpack so that a script inside src/js can resolve code inside common/js if it cannot find anything else locally?
Something like the code below would include common/js/CommonClass.js:

import CommonClass from "CommonClass.js";

This is easy to do for example with compass inside config.rb:

add_import_path "common/scss"
2

There are 2 best solutions below

1
On BEST ANSWER

Webpack accepts multiple resource roots into config.

//webpack.conf.js
module.exports = {
   resolve: {
      root: [__dirname + '/common', __dirname + '/src']
   }
};

Now webpack will search modules in both directories as well. Note that option works only with absolute paths.

See webpack docs for more information.

0
On

As just-boris said, you can use resolve config. The exact setup is differes, depending if you use Webpack 1 or 2.

Webpack 1

resolve: {
  root: [
    path.resolve('./client')
  ]
},

Webpack 2

resolve: {
  modules: [
    path.resolve('./client'),
    'node_modules'
  ]
},

Aliasing is another useful feature, but I personally find above config easier.

See my guide on ES6 Import Statement Without Relative Paths