webpack resolve.root setup with ‘cant find module’ issue only on server side

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'
  ]
}

It seems it could not work only on server side. I think it should be the server not aware of webpack config. You can refer to the project on link https://github.com/ryuever/redux-blog

Author: Fantashit

1 thought on “webpack resolve.root setup with ‘cant find module’ issue only on server side

  1. Same issue in my machine.

    npm webpack version is 1.12.14.

    This issue makes so-called resolve.alias and resolve.root totally useless!!!

Comments are closed.