Grgur's Javascript Corner

ES6 Import Statement Without Relative Paths

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 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.

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'),
'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.

Latest posts

Grgur is a mobile and desktop web application architect and an expert in JavaScript, React, Sencha Ext JS, Angular JS and Webpack integration. One of Grgur's key focus points is performance in his never ending research to find new ways of squeezing out every millisecond out of rendering engines.