Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I resolve absolute require paths with webpack?

Tags:

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?

like image 733
ericgio Avatar asked Oct 10 '15 20:10

ericgio


People also ask

How can webpack help you avoid relative path imports?

React emphasises on modular code and component architecture. Dividing the app into presentational and container components makes the code more readable and also reusable.

What does resolve in webpack do?

Webpack uses resolve. extensions to generate all the possible paths to the module, e.g. Webpack would then proceed to lookup each of those paths until it finds a file.

How do you specify an absolute path?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).


1 Answers

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

like image 179
Jack Allan Avatar answered Oct 31 '22 21:10

Jack Allan