繁体   English   中英

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

[英]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在浏览器中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的代码拆分,以便只捆绑每个页/节所需的依赖关系。 或者,您可以考虑使用浏览器端的require()加载程序,例如RequireJS

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM