如何使用Create-React-App在打字稿中运行NodeJS脚本?
我有一个使用以下版本创建的应用程序:
- 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具有正确的配置,可以在其start
和build
脚本中编译和运行打字稿文件,则如何运行自定义脚本?
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-scriptsv5
)
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论