ericgio
ericgio

Reputation: 3499

How do I resolve absolute require paths with webpack?

I'm trying to convert an existing website to use webpack, but all the existing require paths are absolute:

var Component = require('/path/to/my/component');

I've been reading through the webpack documentation and also found this answer about resolving paths, but wasn't quite able to solve my problem. When setting resolve.root per the instructions in the answer above, I was able to get the following to work:

var Component = require('./path/to/my/component');
var Component = require('path/to/my/component');

However, I still can't figure out how to get the absolute path working and I would really prefer not to have to go through and update all my paths. Here's the site structure:

/app
  /assets
    /javascripts
      /build
        package.js
      index.js
/node_modules 

webpack.config.js:

var JS_ROOT = __dirname + '/app/assets/javascripts');

module.exports = {
  entry: JS_ROOT + '/index',
  output: {
    path: JS_ROOT + '/build',
    filename: 'package.js'
  },
  ...
  resolve: {
    root: JS_ROOT
  }
};

The error I keep getting is:

Module not found: Error: Cannot resolve 'file' or 'directory' /path/to/component in /Users/<username>/<ProjectRoot>/app/assets/javascripts

What am I doing wrong?

Upvotes: 6

Views: 7146

Answers (1)

Jack Allan
Jack Allan

Reputation: 15004

The resolve.root configuration option may be what you are after. It is documented here: http://webpack.github.io/docs/configuration.html#resolve-root

resolve.root The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

It must be an absolute path! Don’t pass something like ./app/modules.

Example:

var path = require('path');

// ... resolve: { root: [ path.resolve('./app/modules'), path.resolve('./vendor/modules') ] }

Upvotes: 3

Related Questions