26
May

Quick Tip – Webpack And Import Paths

One thing I can’t believe took me so long to figure out is how to have clean import paths when using AMD modules or ES6 in Javascript. I’m talking about this:

var Bar = require('../../foo/Bar');
// or
import Bar from '../../foo/Bar';

How fun is it to look at your folder structure and just add ../until you finally can start going down to the actual file you’re interesting in. That’s so unclean, and Solutions Majisti is all about clean code! Luckily (and sadly a bit) Webpack can solve that problem. Webpack will add a step in your project’s workflow, but to be honest it is awesome enough that using it, even in a native JS-only project, still feels like the benefits outweigh the cons.

resolve.root

This little configuration is what will allow you to have cleaner import (or require) paths. It’s pretty simple too.

module.exports = {
    resolve: {
        extensions: ['', '.js', '.jsx', '.json'],
        root: [
            path.join(root, 'src/js'),
            path.join(root, 'tests')
        ]
    }
};

From that point on, you can var Bar = require('foo/Bar'); and if you have either tests/foo/Bar.jsor src/js/foo/Bar.js, Webpack will resolve it. Of course it means you need to be careful about your naming conventions, but this is something you should be doing already.

As a bonus, notice I added extensions with an array of extensions. This allows us to import a file without having to add the extension to the import. Don’t forget to add an empty string! Setting this option overrides the default way Webpack resolves modules, which will break node_modules import. You can read more here.

IDE Support

I will have to admit, I have not worked with a ton of IDEs, Intellij IDEA is the main one and it does not support Webpack that well, if at all. You will have to manually change import paths when refactoring and Ctrl + Click will not work. That being said, refactoring isn’t so good with Javascript anyway so you’re not really losing anything here.

As far as I am aware, other IDEs do not support it either, but I could very well be wrong here. Let me know in the comments and I’ll update this.

Parting Words

I realize this is very simple, but I have not seen this discussed when people talk about using JS modules or ES6 and even less people just write about it. Coupled with the fact that Webpack’s documentation is… less than ideal (it’s so cramped and weirdly divided), I thought this quick post could be useful to people like me who didn’t know yet about this feature of Webpack.