3

TLDR

Is there a plug-in for Webpack that let's your bring in the module foo/bar/baz using only require('baz')?

FULL

I just came across an interesting plug-in for Babel/NPM:

https://github.com/CentaurWarchief/babel-plugin-global-require

This plug-in let's you require your NPM modules using only the most-specific part of the module's path. For instance, if your filesystem has:

src
  util
    foo
      Bar.js

instead of doing:

require('src/util/foo/Bar');

you can just do:

require('Bar');

If (for instance) you happen to have two "Bar.js" files, you can instead do:

require('foo/bar');

That's awesome ... if you use NPM as your module system. But I'm looking to switch to using Webpack, so my question is: does anything like I just described exist as a Webpack plug-in?

1 Answer 1

4
+50

Webpack has similar feature built in. Add paths to your modules to resolve.root array in your webpack config file.

resolve: {
    root: [path.join(__dirname, 'src/util/foo')]
}

and then require('Bar');

In that case that there is multiple files with same name you have to add their common parent folder to resolve.root array.

Folder structure:

src
  util
    foo
      Bar.js
    bar
      Bar.js

Webpack config:

resolve: {
    root: [path.join(__dirname, 'src/util')]
}

and then

require('foo/Bar');
require('bar/Bar');

EDIT

Use absolute paths. Thanks ErikPhipps for comment.

2
  • Perfect, that was exactly what I was looking for, thanks! Nov 10, 2015 at 18:25
  • 1
    The documentation mentions that the path must be absolute: "It must be an absolute path! Don’t pass something like ./app/modules."
    – ErikPhipps
    Nov 11, 2015 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.