Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using webpack and babel with files from parent project directory

I have a project set up like this and I'm trying to require file-a.js from file-b.js.

project-name/
  node_modules/
  src/
    file-a.js
  tools/
    tool-name/
      node_modules/
      src/
        file-b.js
      webpack.config.js
      package.json
  package.json

My webpack 1.13.0 configuration was working until I added babel-loader 6.2.4 with babel-preset-es2015 6.6.0. Then I started getting error messages.

ERROR in /home/dan/dev/dan/project-name/src/file-a.js Module build failed: Error: Couldn't find preset "es2015" relative to directory "/home/dan/dev/dan/project-name/src"

Now I have a hunch that this is happening because it's looking for babel-preset-es2015 in the upper package.json. I can make this error go away by installing it at that level, but then I get a similar message about the babel module not being there.

I've tried all sorts of things, symlinked the upper src directory into the inner project, used resolve.root and resolve.alias to try and manually resolve the folder without the nested path. Used context to set the project root as the outer folder, but it still picked up the wrong node_modules.

How can I force webpack to use the correct node_modules folder?

like image 911
Dan Prince Avatar asked May 17 '16 08:05

Dan Prince


People also ask

Where do I put Babelrc file?

babelrc file is your local configuration for your code in your project. Generally you would put it in the root of your application repo. It will affect all files that Babel processes that are in the same directory or in sibling directories of the . babelrc .

Does Babel run before Webpack?

For . js and . jsx files, we tell Webpack to use babel-loader which makes Webpack run these files through Babel before bundling them.

Can Webpack work without Babel?

No unless all dependencies of your project supports ES6. There is one serious incompatibility: import is asynchronous while require() is synchronous.


1 Answers

By default webpack looks in ./node_modules, ../node_modules, and ../../node_modules.

To force it to only use a specific directory, you can set an absolute path for the module modulesDirectories property in the resolve section:

module.exports = {
  // ...
  resolve: {
     modulesDirectories: [path.join(__dirname, 'node_modules')]
  }
}

More details on moduleDirectories in webpack's documentation

like image 166
Koen. Avatar answered Sep 22 '22 00:09

Koen.