Make absolute paths relative to the project root in Webpack

I am going to answer this slightly differently without using resolve.root. Everything @dresyecat said is correct. However, I just went through the same exercise of moving from relative paths everywhere to module paths. Here is the doc that explains the three different types of paths you can use in the import statement.

You are asking to use a module path, which I believe is the preferred way to go.

The problem is that by default, module paths only work with things imported via npm because the new modules variable on resolve defaults to ["node_modules"]. This lets you import 3rd party code from npm really easily. But it means importing your code with a module path needs a config change. BTW, the modules used to be called moduleDirectories in previous versions. Here are the docs for the resolve variable configuration.

Ok assuming you have a directory structure like this:

project/
    webpack.config.json
    js/
        components
        actions

You can set the modules directory to be:

resolve: {
    extensions: [ '.ts', '.js', '*' ],
    modules: [ path.resolve(__dirname, "js"), "node_modules"]
}

A couple important points:

  • Be sure to include the "node_modules" if you are using npm to pull in 3rd party code, or your imports of those will start to fail
  • Be sure to import the path component in your configuration so that path is defined

    var path = require('path');

Then you can use the following (as was pointed out - without the leading /) to import your components using the module path form:

import "actions/fooAction";

The resolve.root option does not modifiy how file modules are resolved.

A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.

The / resolves to the root of your file system.

Maybe what you want is to resolve your js folder as a modules directory.

webpack.config.js

resolve: {
  root: path.resolve('./js')
}

With this configuration added to your config file will tell webpack to resolve any import or require relative to your js folder. Then, instead of using

import foo from '../actions/fooAction'

you will be able to:

import foo from 'actions/fooAction`

Mind the lack of / at the beginning.

Tags:

Webpack