简体   繁体   中英

Resolving javascript files using webpack

My webpack.config.js contains something like:

...
module.exports = {
  entry: './app.js',
  output: { path: __dirname + "/dist/", filename: 'bundle.js' },
  resolve: {
    root: path.resolve('./js')
  }
  ....
}

The documentation suggests resolve can have a root value. But I get the error below.

$ node ./node_modules/webpack/bin/webpack.js
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.resolve has an unknown property 'root'. These properties are valid:
   object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }

I get the same with modulesDirectories. Not sure which, or if either, I should be using. Any idea how I can pull my JS files in?

You've looked at the documentation for webpack 1. Webpack 2 removed resolve.root and unified it to resolve.modules , as shown in the Migration Guide of the official webpack 2 docs.

The correct way of doing it with webpack 2 is:

resolve: {
  modules: [path.resolve('./js'), 'node_modules']
}

But you might have misunderstood what the option does. It does not include all the files in those paths. Webpack starts from your entry point and processes just the files that are being imported (see also Core Concepts ). So if you want webpack to include your JavaScript files, you need to import them at some point.

Instead this option tells webpack where to look for the module when you import it (not with a relative path). By default only node_modules is used for resolving Module paths , just like Node.js does it.

For example with this directory structure:

js
├─ components
│   └─ main.js
└─ utils
    └─ helper.js

You can import the helper.js file from anywhere in your project with:

import helper from 'utils/helper';

Whereas if you didn't add js/ to the resolve.modules you would need to import it with a relative path. So for instance in js/components/main.js the import would look like this:

import helper from '../utils/helper`;

Obviously the relative path is different depending on which directory you're in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM