我目前正在尝试为ReactJ建立一个州管理库。但是,一旦我将其实施到我的React项目中(创建create-react-app),它开始删除此错误:

Failed to compile.

path/to/agile/dist/runtime.js 116:104
Module parse failed: Unexpected token (116:104)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|       if (subscriptionContainer instanceof sub_1.CallbackContainer) subscriptionContainer.callback(); // If Component based subscription call the updateMethod which every framework has to define
|
>       if (subscriptionContainer instanceof sub_1.ComponentContainer) if (this.agileInstance.integration?.updateMethod) this.agileInstance.integration?.updateMethod(subscriptionContainer.component, Runtime.formatChangedPropKeys(subscriptionContainer));
|     }); // Log Job
|

如果我评论错误中提到的突出显示的代码行,它将跳到另一点并在那里抱怨。但这不是语法错误,因为当时的TypeScript也会在IDE中抱怨。

How the tool works: 一开始,您必须定义一个框架,在这种情况下,react。然后,您可以创建一个状态并通过钩子订阅该状态为react功能组件。用于将状态结合到react组件的钩子简单地创建一个触发重新渲染的回调(通过突变useReducer) 并将此回调分配给订阅的 State。

如果您想了解更多查看此存储库:https://github.com/agile-ts/agile

Dependencies:

第三方国家管理库:

  "dependencies": {
    "@types/chai": "^4.2.12",
    "@types/mocha": "^8.0.2",
    "chai": "^4.2.0",
    "eslint-config-prettier": "^6.11.0",
    "mocha": "^8.1.1",
    "prettier": "2.0.5",
    "ts-node": "^8.10.2",
    "tsc-watch": "^4.1.0",
    "tslib": "^2.0.0",
    "typescript": "^3.9.7"
  }
  • 节点:v14.8.0

React项目:

"dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@types/jest": "^24.0.0",
    "@types/node": "^12.0.0",
    "@types/react": "^16.9.0",
    "@types/react-dom": "^16.9.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.3",
    "typescript": "~3.7.2",
    "agile-framework": "file:../../"
  },
  • react:16.13.1
  • NPM:6.14.7

答案

问题是您将ES2020发射到dist/。如果您看线路,它会抱怨:

if (subscriptionContainer instanceof sub_1.ComponentContainer) if (this.agileInstance.integration?.updateMethod) this.agileInstance.integration?.updateMethod(subscriptionContainer.component, Runtime.formatChangedPropKeys(subscriptionContainer));
                                                                                              // ^^                                         // ^^

您可以看到它正在使用可选的链接运算符在发射代码中。因此,库的消费者将需要具有适当的配置来处理这种代码。您的示例消费者CRA应用程序正在使用Babel;虽然设置 具有可选链接的转换,它仅在React App本身的源代码上运行,不是它的依赖项(包括您的库)。

修复它的一种选择是发射较少的现代代码,这将减少消费者所需的配置量。例如,如果您使用以下设置为目标ES6,则tsconfig.json

{
    "target": "ES6",
    "lib": ["DOM", "ES6", "DOM.Iterable", "ScriptHost", "ES2016.Array.Include"],
    // ...
}

React应用程序至少可以启动,而无需更改源代码。

来自: stackoverflow.com