Webpack - how to resolve a module recursively

This is my folder structure.

project |app |component |Header.js |Home.js |sass |header.scss |node_modules |moment 

This is how I want to import modules into Home.js

 import Header from 'Header' import 'header.scss' import moment from 'moment' 

How to configure webpack so that it understands which module I'm trying to import?

+7
reactjs webpack
source share
5 answers

This is how I do it. You need to manually add more catalogs to the array if there is a new one.

 resolve: { modulesDirectories: [ 'app', 'app/component', 'app/sass', 'node_modules', 'bower_components' ] }, 
+2
source share

You do not specify relative paths in import statements. moduleDirectories is not intended to list all directories, but only to the roots.

Your import statements should probably look like this: (Assuming they are available from app/ )

 import './component/Header' import './sass/header.scss' 

Then moduleDirectories should include only the "application" and not its subfolders.

+1
source share

Please refer to this

https://webpack.imtqy.com/docs/configuration.html#resolve

and make the necessary configuration in your web package to resolve paths at runtime

+1
source share

You can use aliases Babel

https://www.npmjs.com/package/babel-plugin-module-alias

And set up something like this:

 { "src": "./app/component", "expose": "component" } 

Then

 import Header from 'component/Header'; 
+1
source share

This link should help:

http://xabikos.com/2015/10/03/Webpack-aliases-and-relative-paths/

But if your webpack.[production/dev].config.js is located in /project , then the alias section is required in the resolve section; something like that:

 module.exports = { entry: path.resolve(__dirname, "./app/component/Home.js"), output: { path: __dirname, filename: "bundle.js" }, module: { loaders: [ { test: /\.css$/, loader: "style!css" } ] }, resolve: { alias: { moment: path.resolve(__dirname, './node_modules/moment/moment.js') } } }; 
0
source share

All Articles