JavaScript: Module Resolution with Webpack & Babel

2018-06-04 ·

You can simplify the following code:

import MyComponent from '../../../components/MyComponent';

into this:

import MyComponent from 'components/MyComponent';

This way components can be found no matter where they are in the file hierarchy. This article will show two solutions: one using Webpack and another one using Babel.

Using Webpack

Inside webpack.config.js add the following alias definition under resolve.

resolve: {
  alias: {
    components: path.resolve('./your/path/to/components'),
  },
}

Using Babel

Use babel-plugin-module-resolver:

npm install --save-dev babel-plugin-module-resolver

Declare your paths under root inside .babelrc:

{
  "plugins": [
    ["module-resolver", {
      "root": ["./src/**", "./src/your/components/**"]
    }]
  ]
}

You can also define an alias for some paths, which will be used as a prefix, e.g.

{
  "plugins": [
    ["module-resolver", {
      "root": ["./src/**", "./src/your/components/**"]
      "alias": {
        "@test": "./test",
      }
    }]
  ]
}

Now you can references everything from ./test directory by prefixing it name with @test:

import MyTest from '@test/path/to/MyTest';
Copyright © 2018 All rights reserved.
Powered by Kulfon.