Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 668
angry kiwi Avatar asked Jun 21 '16 18:06

angry kiwi


3 Answers

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.

like image 119
Michael Pratt Avatar answered Oct 22 '22 14:10

Michael Pratt


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'
    ]
},
like image 1
angry kiwi Avatar answered Oct 22 '22 16:10

angry kiwi


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';
like image 1
Michael Rasoahaingo Avatar answered Oct 22 '22 15:10

Michael Rasoahaingo