【问题标题】:Add support for experimental syntax 'classProperties' in an npm package在 npm 包中添加对实验语法“classProperties”的支持
【发布时间】:2020-08-15 20:10:33
【问题描述】:

我想发布一个带有一些功能的 npm 包,以便在我的 create-react-app 项目中使用它。当我从 create-react-app 项目中的 js 文件导入函数时,它工作正常。但是当我将它作为 npm 包安装时,我收到一个错误:Support for the experimental syntax 'classProperties' isn't currently enabled

我尝试将以下代码添加到 npm 包的 package.json 文件中:

"devDependencies": {
  "@babel/plugin-proposal-class-properties": "^7.8.3"
},
"babel": {
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

但它并没有解决问题,我得到了同样的错误。

我还需要在我的 npm 包中添加什么依赖项才能在我的 create-react-app 项目中使用它?还是在没有这种实验性语法的情况下重写函数更好?

【问题讨论】:

    标签: javascript node.js npm ecmascript-6 babeljs


    【解决方案1】:

    您需要在构建依赖项中添加 plugin-proposal-class-properties

    设置步骤的工作示例:https://github.com/hitsio/Node-JS-ES6

    以下是设置 Babel 以将 ES6 预编译为 JavaScript 的步骤

    1. 安装Babel

    npm install --save-dev @babel/core @babel/cli

    1. 安装Babel Preset & Class Properties Plugin

    npm install @babel/preset-env --save-dev
    npm install --save-dev @babel/plugin-proposal-class-properties

    @babel/preset-env 允许您使用最新的 JavaScript,而无需微观管理目标环境需要哪些语法转换(以及可选的浏览器 polyfill)。这既让你的生活更轻松,也让 JavaScript 包更小!

    @babel/plugin-proposal-class-propertiesES6 class 合成糖转换为 JavaScript __Prototype__

    1. 在项目的根目录下创建.babelrc文件并在.babelrc

      中添加以下代码
       {
       "presets": ["@babel/preset-env"],
       "plugins": ["@babel/plugin-proposal-class-properties"] 
       }
      

    【讨论】:

      【解决方案2】:

      基于这个SO answer,我做了以下事情:

      .npmignore

      /src
      

      .gitignore

      /lib
      /node_modules
      

      安装 Babel

      $ npm install @babel/core @babel/cli @babel/preset-env --save-dev
      

      安装@babel/plugin-proposal-class-properties

      $ npm install --save-dev @babel/plugin-proposal-class-properties
      

      package.json

      "main": "lib/index.js",
      "scripts": {
        "prepublish": "babel src -d lib"
      },
      "babel": {
        "presets": [
          "@babel/preset-env"
        ],
        "plugins": [
          "@babel/plugin-proposal-class-properties"
        ]
      }
      

      【讨论】:

        【解决方案3】:

        如果有人在使用 react-native-calendars 并遇到此错误,请关注 this 链接。

        【讨论】:

          猜你喜欢
          • 2019-02-13
          • 2021-04-26
          • 2020-03-06
          • 2022-10-22
          • 2020-02-09
          • 2020-08-07
          • 1970-01-01
          • 2019-11-10
          • 1970-01-01
          相关资源
          最近更新 更多