node.js - 为什么要在 Node 中使用 webpack-node-externals?

标签 node.js webpack

我正在使用 webpack 来捆绑我的 typescript nodejs 代码。

我使用 webpack-node-externals 来避免编译期间 node_modules 中的错误。

webpack-node-externals 表示,允许您定义外部 - 不应捆绑的模块。

但是为什么? Webpack 应该捆绑我开始捆绑所需的一切,对吗?它可以提取和删除我不使用的模块。 (例如摇树)。

如果我使用 webpack-node-externals,那么我必须在我的 prod 文件夹中执行 npm i 以获取所有依赖项。

我认为这是错过了 webpack 可以做的事情。对吧?

最佳答案

我认为你是对的,在你的情况下,捆绑到一个文件中会更有意义。 webpack-node-external似乎是为使用 NodeJS 库而不是独立应用程序而设计的。来自他们的 doc :

When writing a node library, for instance, you may want to split your code to several files, and use Webpack to bundle them. However - you wouldn't want to bundle your code with its entire node_modules dependencies, for two reasons:

  1. It will bloat your library on npm.
  2. It goes against the entire npm dependencies management. If you're using Lodash, and the consumer of your library also has the same Lodash dependency, npm makes sure that it will be added only once. But bundling Lodash in your library will actually make it included twice, since npm is no longer managing this dependency.

As a consumer of a library, I want the library code to include only its logic, and just state its dependencies so they could me merged/resolved with the rest of the dependencies in my project. Bundling your code with your dependencies makes it virtually impossible.

我不同意认为 Webpack 不是为捆绑 Node 脚本而设计的评论,considering that Webpack has a specific setting for just that (target) .不幸的是,有太多的第三方库不能很好地与 Webpack 配合使用(正如我今天刚刚发现的那样),所以从实用的角度来说,你最好还是在分发文件夹中安装模块。

关于node.js - 为什么要在 Node 中使用 webpack-node-externals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52714984/

相关文章:

javascript - Node.js 从回调内部返回主循环

node.js - 安装不同版本的 NodeJS

node.js - 无法使用 stdin 读取输入

javascript - ReactJS 与 Webpack : Uncaught ReferenceError: require is not defined

css - 原始 css 未加载到我的 bundle.js Angular 2 应用程序中

node.js - 如何使用 google drive api v3 重命名文件? Electron , Node

javascript - 无法在 Node js中安装强大的

javascript - Webpack,html-webpack-plugin,错误: Child compilation failed

javascript - 在 webpack 2 中混合长期缓存和代码分割

使用 --stats-json 构建 Angular 6 不生成 stats.json 文件