15

I am trying to build a grpc web client and I need to pack the code to resolve the require statements.

I have compiled the protos to js and it works if I have them in the current folder where I have installed the node modules.

The problem is if I have the compiled proto in some other place and I require them from there, webpack looks for the node modules in that path.

From my client.js

working version:

const {StopRequest, StopReply} = require('./work_pb.js');

Problematic version:

const {StopRequest, StopReply} = require('../../../messages/proto/output/work_pb.js');

In this last case it looks for the node modules in ../../../messages/proto/output/. The node modules are installed in the current path where my client.js is and from where I ran npx webpack client.js.

ERROR in /home/xxx/yyy/zzz/messages/proto/output/work_pb.js
Module not found: Error: Can't resolve 'google-protobuf' in '/home/xxx/yyy/zzz/messages/proto/output'
 @ /home/xxx/yyy/zzz/messages/proto/output/work_pb.js 11:11-37
 @ ./client.js

How do I tell webpack to look in the current path for the node modules and not in the path of the compiled proto?

codentary
  • 993
  • 1
  • 14
  • 33

1 Answers1

21

You can specify resolve.modules to customize the directory, where Webpack searches for modules with absolute import paths:

// inside webpack.config.js
const path = require('path');
module.exports = {
  //...
  resolve: {
    modules: [path.resolve(__dirname, 'node_modules'), 'node_modules']
  }
};

This will let node_modules inside your project root (where webpack config resides) take precedence over the default setting "node_modules", which resolves paths via node module resolution algorithm.

More infos: Webpack docs: Module Resolution

ford04
  • 66,267
  • 20
  • 199
  • 171
  • Even better.. I moved `package.json` and `webpack.config.js` outside of my `app` folder (one level up) and I can still run `npm install` and `npx webpack client.js` from the `app` folder. I guess it checks up the hierarchy. – codentary Aug 18 '19 at 13:50
  • 1
    Yeah, `npm install` will traverse up to the nearest package.json or node_modules, if not found in cwd. Concerning webpack, I am not so sure, what defaults it will use then. I think, it's worth to make everything as explicit and comprehensible as possible. That's the reason why I prefer to pass in the config via `--config`. – ford04 Aug 18 '19 at 15:21