Webpack Uncaught ReferenceError:从bundle.js中删除node_modules后未定义require

Cle*_*ent 5 javascript commonjs webpack

bundle.js      2.83 kB   0  [emitted]  main
bundle.js.map  3.36 kB   0  [emitted]  main
Run Code Online (Sandbox Code Playgroud)

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

bundle.js      743 kB       0  [emitted]  main
bundle.js.map  864 kB       0  [emitted]  main
Run Code Online (Sandbox Code Playgroud)

这显着减少了束大小.但我在浏览器中收到错误: 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]
}
Run Code Online (Sandbox Code Playgroud)

Aur*_*001 10

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

如果要减少包大小,请考虑使用Webpack的代码拆分,以便只捆绑每个页/节所需的依赖关系.或者,您可以考虑使用require()诸如RequireJS之类的浏览器端加载器.

使用externals对于分发服务器端节点库非常有用,您可以期望库的使用者提供依赖关系,而不是将它们与库捆绑在一起.

有关该文档externals的评论也值得一读,以便进一步了解该问题.