0

In my express app I use Import and Export statements. I have the "type": "module" line in my package.json file. I can run the app using Node before bundling it with Webpack.
After I've bundled it into one JS file, Webpack converts the Imports to "require". Then I get the "ReferenceError: require is not defined" error when I try to run the bundled JS file using Node.

I would like to use modules instead of converting my project to commonjs.

Webpack v.5
Node v.14
Express v.4

Abet
  • 1
  • 1
  • Why are you using webpack for the server side? What's the goal? (isomorphic code, using certain webpack plugins, or maybe making deployment easier?) – 1j01 Dec 16 '21 at 21:39
  • `require` is not defined probably because of the `"type": "module"` in `package.json`; so you could either remove that in order to run the bundle (which may be impractical), or configure webpack to output with import/export syntax. This may be helpful, although it doesn't mention ES6 modules: https://stackoverflow.com/questions/29911491/using-webpack-on-server-side-of-nodejs – 1j01 Dec 17 '21 at 05:20
  • I'm using Webpack, because it seems to be the industry standard for production apps and I want to learn how to use it. Is there a better way to bundle server side code? – Abet Dec 18 '21 at 12:40
  • Well, you don't need to, generally! Bundling is normally used only on the client. Bundling for the client already lets you write isomorphic code, that is, to share code between the server and client. If you want to publish your server so it can be installed easily, you can publish it to npm and then npm will take care of dependencies. So if you don't have a specific reason to do bundling for your server, I wouldn't recommend it! – 1j01 Dec 19 '21 at 00:50

0 Answers0