Webpack Uncaught ReferenceError: require is not detected after removing node_modules from bundle.js

bundle.js 2.83 kB 0 [emitted] main bundle.js.map 3.36 kB 0 [emitted] main 

When I add the code below with custom externals, I can remove node_modules from directly including bundle.js in the output.

 bundle.js 743 kB 0 [emitted] main bundle.js.map 864 kB 0 [emitted] main 

This greatly reduces the size of the package. But in the browser I get an error: Uncaught ReferenceError: require is not defined in the browser. Does anyone know how to fix this problem?

 var path = require("path"), fs = require("fs"); // return what in the node modules folder apart from ".bin" const nodeModules = fs .readdirSync("./node_modules") .filter(d => d != ".bin"); /** * Remove non-direct references to modules from bundles * * @param {any} context * @param {any} request * @param {any} callback * @returns */ function ignoreNodeModules(context, request, callback) { // IF someone is importing a module eg "import {chatModule} from // "./components/chat" using a relative path, then we're okay with them bringing // in into the bundle if (request[0] == ".") return callback(); // IF someone is doing "import {Subject} from "rxjs/Subject" only want to know // if first part is a node_module const module = request.split("/")[0]; if (nodeModules.indexOf(module) !== -1) { // append "commonjs " - tells webpack to go and grab from node_modules instead // of including in bundle return callback(null, "commonjs " + request); } return callback(); } module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js" }, devtool: "source-map", resolve: { extensions: ["", ".ts", ".tsx", ".js"] }, module: { loaders: [ { test: /\.ts(x?)$/, loader: "ts-loader" } ] }, // Runs our custom function everytime webpack sees a module externals: [ignoreNodeModules] } 
+5
source share
1 answer

Your package is smaller because you do not include your node_modules , but this leads to a fundamental problem: you no longer send your dependencies to the browser, so your code cannot work at all . As you probably know, browsers do not support require() , so your current ignoreNodeModules function tells Webpack to skip binding them and leave it in require() , but the browser does not know how to handle this.

If you want to reduce the size of the batch, consider using separation so that you only associate the dependencies needed for each page / section. Alternatively, you can use the require() loader on the browser side, such as RequireJS .

Using externals really only useful for distributing Node server libraries where you expect users of your library to provide your dependencies rather than linking them to your library.

Comments on externals documentation also deserve attention for further discussion of the problem.

+9
source

Source: https://habr.com/ru/post/1260782/


All Articles