如何使用Create-React-App在打字稿中运行NodeJS脚本?

发布于 2025-02-11 15:20:26 字数 1113 浏览 0 评论 0原文

我有一个使用以下版本创建的应用程序:

  • Node v16.15.1
  • typescript v4.3.2 v4.3.2
  • active-scripts v4.0.3 <v4.0.3 < /code>(尽管我对需要React-Scripts v5的答案开放)

我想使用与React App相同的配置来编译并运行在打字稿中编写的可执行nodejs脚本。此外,我需要能够从应用程序的其余部分导入文件

例如,

import foo from '../util/foo'

const result = foo(process.argv[2])

console.log(result)

我获得的最接近的是:

npx ts-node --esm src/scripts/myscript.ts

但是,只有在我添加“ type”:“ module”时,它才能有效。即使那样,我的脚本也会在导出关键字上断开。

我可以在scripts文件夹中创建package.json“ type”:“ module”tsconfig扩展了应用程序配置:

{
  "extends": "../tsconfig.json",
  "include": ["**/*.ts"],
  "compilerOptions": {
    "noEmit": false,
    "outDir": "build"
  }
}

但是,这会导致导入的打字稿文件中的导入/导出问题。

如果React-Scripts具有正确的配置,可以在其startbuild脚本中编译和运行打字稿文件,则如何运行自定义脚本?

I have an app I created with create-react-app, using the following versions:

  • Node v16.15.1
  • Typescript v4.3.2
  • react-scripts v4.0.3 (though I am open to answers that require react-scripts v5)

I want to compile and run an executable NodeJS script written in Typescript using the same configuration as the React App. Additionally, I need to be able to import files from the rest of the app into my script.

e.g. /src/scripts/myscript.ts

import foo from '../util/foo'

const result = foo(process.argv[2])

console.log(result)

The closest I have gotten is:

npx ts-node --esm src/scripts/myscript.ts

However it only works if I add "type": "module" to my package.json, which breaks npm start. Even then, my script breaks on the export keyword.

I can create a package.json in the scripts folder with "type": "module" and a tsconfig that extends the app config:

{
  "extends": "../tsconfig.json",
  "include": ["**/*.ts"],
  "compilerOptions": {
    "noEmit": false,
    "outDir": "build"
  }
}

But this runs into issues with import/export in the imported typescript files.

If react-scripts has the correct config to compile and run Typescript files in its start and build scripts, how do I run a custom script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文