ES6 Import Statement Without Relative Paths Using Webpack

   DevOps and Tools

The ES2015 module system is probably familiar to you by now. If you’ve used it, you might have faced the familiar relative path inclusion problem.

Using relative paths for imports makes your code base very hard to maintain, not to mention the hassle required to figure out where the inclusion is relative to the current path. If your code resembles the example below, today might be your lucky day!

import Header from '../../components/Header';
import Grid from '../../components/Grid';
import TransactionForm from '../TransactionForm';
import TransactionSummary from '../TransactionSummary';
import * as AppActions from '../../actions';

Import Path Resolver

With a very minor tweak to our Webpack configuration, we can get it to load files relative to the app root. Actually, we can configure the resolver to load from multiple root folders and our import declaration will get a major overhaul.

import Header from 'components/Header';
import Grid from 'components/Grid';
import TransactionForm from 'containers/TransactionForm';
import TransactionSummary from 'containers/TransactionSummary';
import * as AppActions from 'actions';

That looks much better, doesn’t it?

Webpack 1.x Path Resolver Configuration

Here’s the trick that makes the above possible:

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

Use this in your Webpack v1.x configuration. You might already have a ‘resolve’ setting in there. Keep everything there, but add a root key and specify all the folders that you would like to load your files from. In my case it’s the ./client/ folder.

Adding too many folders may not turn out to be a good idea so don’t go wild with it either. Recursive search in too many paths may result in slower webpack builds, and it makes it harder to keep track of where the imports are coming from.

Webpack 2.x Path Resolver Configuration

In Webpack 2, resolvers from root (as used above), modulesDirectories, and fallback settings will merge into a single property – modules. Here is how we can do the same trick in Webpack 2:

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

You can specify a number of directories in modules, but make sure not to forget node_modules or npm package dependencies will fail to load.

Sample Project With Webpack Configuration

You can see the above setup in a sample project that uses Webpack + Redux + React. Feel free to use it in your own projects.

Please share this if you think your network might find this information helpful. Let me know how this worked for you in the comments below or on Twitter.


Like What You See?

Got any questions?