Getting large cryptic errors and warnings when trying to use mongoose with webpack Getting large cryptic errors and warnings when trying to use mongoose with webpack mongoose mongoose

Getting large cryptic errors and warnings when trying to use mongoose with webpack


Your webpack config that handles the server code should have a few extras to avoid issues.

Try adding the following:

    target: 'node',    output: {        ...,        libraryTarget: 'commonjs',    },    externals: [        /^(?!\.|\/).+/i,    ],

Setting the target to node makes webpack aware that you're working in a Node context, and not in a browser. Adding libraryTarget: 'commonjs' will make webpack use simple require calls to get functions from external libraries.

Then an important thing happens in the regex in externals. It basically excludes any requires that use a non-relative path from the bundle. That way if you do import 'react'; it won't be packaged by webpack, but if you do import './components/MyComponent.js';, it will.

That will also mean that you have to make sure your node_modules directory is included with your built server code.

Why do all this? Because Node uses a lot of native modules that can't be bundled right. They are specific to your exact version of Node on your specific OS, and you can't just pull those into a Javascript bundle. You want your own code to go through webpack, and all stuff from node_modules to just be accessed like any Node project.

Now if you get those warnings/errors in your browser bundle, it means that you're probably requiring/importing modules that only work on the server in your browser bundle. Make sure you only require them in files that are only used on the server. Alternatively, selectively require them. How you can do selective requires based on the build type can be found here: Can I detect if my script is being processed by Webpack?