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

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

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

当我使用自定义外部添加下面的代码时,我可以删除 node_modules,使其不直接包含在 bundle.js 输出中。

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

这显着减小了包的大小。 但我在浏览器中收到错误提示: Uncaught ReferenceError: require is not defined 在浏览器中。有谁知道如何解决这个问题?

var path = require("path"),
  fs = require("fs");

// return what's 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 e.g. "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]
}

你的包较小,因为你没有包含你的 node_modules,但这会导致一个根本问题:你不再将你的依赖项发送到浏览器,所以你的代码可以'完全 运行。您可能知道,浏览器本身并不支持 require(),因此您当前的 ignoreNodeModules 函数告诉 Webpack 跳过捆绑它们并留在 require(),但浏览器不知道如何处理它。

如果您想减小包的大小,请考虑使用 Webpack 的 code splitting so that you only bundle dependencies that are needed for each page/section. Alternatively, you could consider using a browser-side require() loader such as RequireJS

使用 externals 仅对分发服务器端 Node 库非常有用,在这种情况下,您希望库的使用者提供您的依赖项,而不是将它们与您的库捆绑在一起。

关于 documentation about externals 的评论也值得一读,以了解有关该问题的更多背景信息。