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这样您就可以只捆绑每个页面/部分所需的依赖项。或者,您可以考虑使用浏览器端 require() 加载程序,例如 RequireJS .
使用 externals 仅对分发服务器端 Node 库非常有用,在这种情况下,您希望库的使用者提供您的依赖项,而不是将它们与您的库捆绑在一起。
关于 documentation about externals 的评论也值得一读,了解有关该问题的更多背景信息。
关于javascript - Webpack 未捕获引用错误 : require is not defined after removing node_modules from bundle. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40958895/