angry kiwi
angry kiwi

Reputation: 11485

Webpack - How to resolve 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 import modules in Home.js

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

How to config webpack so that it understand what module I'm trying to import?

Upvotes: 9

Views: 5565

Answers (5)

Resonance
Resonance

Reputation: 3796

This link should help:

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

But essentially if your webpack.[production/dev].config.js file is in /project it will need an alias section within a resolve section; something like this:

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

Upvotes: 1

angry kiwi
angry kiwi

Reputation: 11485

This is how I do it. Gonna have to manually add more directory in the array when there is new one.

resolve: {
    modulesDirectories: [
        'app',
        'app/component',
        'app/sass',
        'node_modules',
        'bower_components'
    ]
},

Upvotes: 1

Michael Rasoahaingo
Michael Rasoahaingo

Reputation: 1089

You can look at use Babel aliases

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

And configure something like this:

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

Then

import Header from 'component/Header';

Upvotes: 1

John Peter
John Peter

Reputation: 441

Please refer this

https://webpack.github.io/docs/configuration.html#resolve

and do necessary configuration in your webpack to resolve paths in runtime

Upvotes: 0

Michael Pratt
Michael Pratt

Reputation: 3496

You're not specifying relative paths in the import statements. moduleDirectories is not intended to list out every directory, only the roots.

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

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

Then moduleDirectories only needs to include 'app', not subfolders thereof.

Upvotes: 1

Related Questions