【问题标题】:Automatically minify all node_modules自动缩小所有 node_modules
【发布时间】:2017-12-01 20:25:30
【问题描述】:

是否有一个工具可以让你运行它来获取 node_modules 中的每个 javascript 文件并用它的缩小版本替换它?

我意识到这是一个非常简单的任务,可以通过循环遍历所有 .js 文件并将它们传递给压缩器来完成,但我的实现会很慢,并且希望有人可能有一种“更聪明”的方式来做这件事。

【问题讨论】:

  • 您能详细说明您希望缩小项目中的所有节点模块吗?
  • @kentor 减少 node_modules 文件夹的总大小。
  • 您的 node_modules 文件夹有多大,甚至会成为问题?此外,任何时候更新包都必须重新缩小。
  • 好吧,我已经知道您想要最小化 Node 模块文件夹以节省空间,但是您为什么要首先这样做呢?你不应该提交节点文件夹吗?
  • @kentor 这是针对无服务器应用程序的。在所有无服务器平台(Google、Amazon、Azure)中,您都可以压缩并包含 node_modules。因此,缩小文件将减少工件的大小并大大提高性能。

标签: node.js minify


【解决方案1】:

我有一个类似的问题要解决,与要在 Lambda AWS 层框架上部署的层的尺寸有关。 在我的情况下,问题与输出层开始增加其维度的事实有关,并且从 AWS 的限制和性能的角度来看都存在问题(尝试考虑加载一层,例如 100MB与 40MB 之一相比)。

无论如何,鉴于该概述,我设法执行了三个步骤,以实现对 node_modules 文件夹的适当压缩,然后是整体层大小。

  1. 使用 modclean 根据预定义和自定义 glob 模式从 node_modules 目录中删除不必要的文件和文件夹。

  2. 使用node-prune 脚本从node_modules 目录中删除不必要的文件,例如markdown、typescript 源文件等。

  3. 最后我们可以运行minify-all 一个函数来缩小嵌套文件夹中的所有javascript和css文件。

用于实现适当压缩的 bash 脚本文件如下(在我的例子中,我有一个 249MB node_modules 文件夹,在脚本之后它变成了 120MB):

npm install -g modclean
npm install -g minify-all
npm install -g node-prune

# The following will install the dependencies into the node_modules folder,
# starting from a package.json file.
npm install

# The following line will remove all the unnecessary files and folders
# with caution to all the dependencies.
modclean -n default:safe,default:caution -r

# The following will prune unnecessary files.
node-prune

# The following with minify all the javascript and css files.
minify-all

请注意,第三步需要很长时间才能完成。

【讨论】:

    【解决方案2】:

    我还没有尝试过,但它似乎应该可以工作。你必须安装 webpack

    首先你必须安装 webpack

    $ npm install -g webpack
    

    然后你必须安装 uglify-js 插件

    $ npm install uglifyjs-webpack-plugin
    

    --webpack.config.js

    const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    
    module.exports = {
      entry: './app.js',
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
      },
      optimization: {
        minimizer: [
          new UglifyJsPlugin({
            test: /\.js(\?.*)?$/i,
          }),
        ],
      }
    };
    

    然后在你的终端运行

    $ webpack --config webpack.config.js
    

    【讨论】:

    • 这有多快(相当慢)?我假设这需要很长时间?
    • 非常快。最多几分钟。
    猜你喜欢
    • 2021-06-24
    • 2011-10-09
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多