ryu
ryu

Reputation: 661

webpack resolve.root setup with 'cant find module' issue

This is a react project with webpack for bundling jsx file, and the folder tree is list as follows:

.
|-- app
|   |-- client.jsx
│   |-- components
|     | -- ArticleCommentListItem.jsx
|     | -- ArticleCommentListItemFooter.jsx
|-- server
|   | -- index.js
|-- webpack
|   |-- webpack.config.js

At first, File ArticleCommentListItem.jsx will invoke module ArticleCommentListItemFooter.jsx like below

import ArticleCommentListItemFooter from './ArticleCommentListItemFooter';

After reading the the answer from Alex Klibisz on Resolving require paths with webpack. I want to have a try to call module as format :

import ArticleCommentListItemFooter from 'components/ArticleCommentListItemFooter';

Then I setup in the webpack.config.js file

var webpack_config = {
  entry:{
    app: path.join(__dirname, '..', 'app', 'client')
  },
  output: {
    path: assetsPath,
    filename: '[name].js',
    publicPath: '/assets/'
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss', '.less'],
    root: path.resolve(__dirname, '..', 'app'),
    modulesDirectories: [
      'node_modules'
    ]
  }
}

Everything runs well when bundle client.jsx to app.js, but when I start server with command node server/index.js. It will exit with error

error: Cannot find module 'components/ArticleCommentListItemFooter'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:289:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/Users/ryu/Documents/git/react/react-blog/app/components/ArticleCommentListItem.jsx:21:37)
    at Module._compile (module.js:425:26)
    at loader (/Users/ryu/Documents/git/react/react-blog/node_modules/babel-register/lib/node.js:128:5)
    at Object.require.extensions.(anonymous function) [as .jsx] (/Users/ryu/Documents/git/react/react-blog/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)

I have also tried to use resolve.alias for webpack.config setup, it still exit with the same error.

resolve: {
  extensions: ['', '.js', '.jsx', '.scss', '.less'],
  alias: {
    components: path.join(__dirname, '..', 'app', 'components')
  },
  modulesDirectories: [
    'node_modules', 'app'
  ]
}

I cant figure out which step I have made mistake.

Upvotes: 3

Views: 3668

Answers (1)

Shiva Nandan
Shiva Nandan

Reputation: 1845

~Remove the ".." before "app" and try again~

Update:

resolve.root and resolve.alias are only applicable to scripts that webpack runs on top of.

Your server/index.js has no idea about the existence of either of those values. So it doesn't know how to find 'components/something.jsx'. You should probably also parse server js through webpack?

Upvotes: 1

Related Questions