ES6 import from root

If you are using Webpack you can configure it via the resolve property to resolve a your import path.

Webpack 1

resolve: {
  root: [
    path.resolve(__dirname  + '/src')
  ]
}......

Webpack 2

resolve: {
  modules: [
    path.resolve(__dirname + '/src'),
    path.resolve(__dirname + '/node_modules')
  ]
}.....

After that you can use

import configureStore from "store/configureStore";

instead of the:

import configureStore from "../../store/configureStore";

Webpack will configure your import path from the passed resolve param.

The same stuff you can do with System.js loader but with it's own config param (it's can be map or path. Check it in the System.js documentation) (if you would like to use it. It's mostly for a Angular 2 case. But I suggest: don't use standard System.js even if you are working with ng2. Webpack is much better).


Had the same issue with React. So i wrote some plugin for babel which make it possible to import the modules from the root perspective - the paths are not shorter - but it's clear what you import.

So instead of:

import 'foo' from '../../../components/foo.js';

You can use:

import 'foo' from '~/components/foo.js';

Here is the Plugin (tested and with a clear README)


The react documentation explain how to do that: https://create-react-app.dev/docs/importing-a-component/#absolute-imports

just add a jsconfig.json in your project root:

{
   "compilerOptions": {
      "baseUrl": "src"
   },
  "include": ["src"]
}