node.js - 在 9.2.0 中创建 Node NPM 模块以支持旧版本的 Node

标签 node.js npm

既然 Node 9.2.0 拥有该语言的所有新功能,我该如何创建一个向后兼容旧版本的 Node 模块?

如果我有一个 Node 9 开箱即用支持的小模块,就像这样。

const {map} = require('lodash')

async function test (...args) {
    return map(args, (item) => {
        return `${item} yeah`
    })
}

module.exports = test

是否有任何方法可以使用 babel 来将其转译为我需要使用 babel env 支持的特定向后版本?有什么方法可以有条件地加载这些 babel 开发依赖项,比如使用安装后脚本通过 Node 4 安装它?

最佳答案

这似乎是一种解决方案,其缺点是它需要 babel-runtime 作为 dep,以防万一,即使当前版本的 Node 不需要它。但在 9.2.0 中,上面的代码是内置代码,它只是被 babel 移动了。

这是一个示例 package.json,安装时它将构建 src。

{
  "name": "example",
  "version": "1.0.0",
  "main": "lib/index.js",
  "scripts": {
    "build": "babel src -d lib",
    "postinstall": "npm run build"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "lodash": "^4.17.4"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1"
  },
  "babel": {
    "plugins": [
      "transform-runtime"
    ],
    "presets": [
      [
        "env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ]
  }
}

关于node.js - 在 9.2.0 中创建 Node NPM 模块以支持旧版本的 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47299881/

相关文章:

node.js - 基本问题生产中的第一个 Node+express+Angular 应用程序

node.js - 如何识别哪些 npm 包只是对等依赖项?

javascript - 从 meteor 中的节点模块导入CSS文件

node.js - 在集成测试中模拟不同的 Passport.js 策略

javascript - TDD原理,如何让测试失败

javascript - 如何在 header 中传递身份验证 token 并帮助获取?

c# - 了解使用 Windows native WPF 客户端进行 ADFS 登录

node.js - 正在运行的Electron应用导致ELIFECYCLE错误

node.js - Angular2 在 angular-cli 下使用指令和 ng build --prod 进行构建

node.js - 我可以从全局安装的软件包访问本地安装的软件包吗?