6

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?

Community
  • 1
  • 1
ericgio
  • 3,094
  • 4
  • 25
  • 44
  • It seems like [this is basically what I want](https://webpack.github.io/docs/resolving.html#resolving-an-absolute-path). I'm confused about where to define the `main` field, though. – ericgio Oct 13 '15 at 00:36
  • did you find a solution? – mpolci Oct 27 '16 at 10:47
  • Probably not very helpful, but I ended up just doing a code mod and changing the paths to be: `var Component = require('path/to/my/component');` – ericgio Dec 30 '16 at 23:14

1 Answers1

3

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') ] }

Jack Allan
  • 14,554
  • 11
  • 45
  • 57
  • `path.resolve()` resolves a path to its absolute form - see https://nodejs.org/docs/latest/api/path.html#path_path_resolve_from_to – Sacho Apr 05 '16 at 07:11