如何使用 Create-React-App 在依赖本地打字稿的节点模块中使用装饰器?

How to use decorator in the depend local typescript based node module with Create-React-App?

我有一个基于 typescript 的 React 项目,它依赖于另一个基于 typescript 的本地项目。我有这样的配置。

React项目的

tsconfig.json:

  "compilerOptions": {
    "target": "esnext",
    ...
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },

package.json:

  "dependencies": {
    ...
    "my-project": "file:../../Path/To/My/Project",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },

如果我在React项目中的jsx文件中使用装饰器就好了:

import React from 'react';
import './App.css';

function deco(target:any){}

@deco                   // < This would be fine
class test{}

function App() {
  return (
    <div className="App">
      <header className="App-header">
      </header>
    </div>
  );
}

export default App;

但是,如果我使用装饰器从外部项目中导入 class,那么在构建时会失败:

import React from 'react';
import './App.css';
// This would case a error when build
import * as mylib from 'my-project/foo_module' 

function App() {
  return (
    <div className="App">
      <header className="App-header">
      </header>
    </div>
  );
}

export default App;
/Path/To/My/Project/foo_module.ts 3:0
Module parse failed: Unexpected character '@' (3:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders      
| import {deco} from 'deco';
|
> @deco()
| export class foo_class

这似乎是关于 webpack 的问题,但我不知道如何在 Create-React-App 中处理它。

听起来你的包正在直接导出未编译的打字稿。通常,编译器不会编译依赖项的输出,因为它希望依赖项目已经完成了。在 My/Project 中,您的 package.json 会将 main 条目指向已编译的 js,而不是未编译的 ts:

{
  "name": "my-library",
  "version": "1.0.0",
  "main": "dist/index.js",
  "scripts": {
    "build": "rm -rf dist && tsc"
  },
  "devDependencies": {
    "typescript": "^4.3.2"
  }
}