node.js - 我如何在一个 TypeScript React 项目中运行一个 node 脚本?
我有一个 React 项目,它包括与一个 API 通信。
我在项目中定义了一个模块,用来抽象化 API 访问。
例如,它有像 addFoo 和 getFoos 这样的方法。我想从一个脚本中使用这个模块,并希望直接在命令行上运行这个脚本。这个脚本的目的是通过 API 将大量数据加载到数据库中。
当我使用普通的.js时,似乎很容易直接运行> node path/to/file。相对导入路径运行良好。
问题
当我使用 .ts 时,它无法工作。它抱怨找不到该模块。
问题
在 React 项目中直接运行 .ts CLI 脚本的正确方法是什么?还是说这样做本身就是错误的?
谢谢!
答案#1
上面 MwamiTovi 的回答很接近,但我还必须设置 {"module": "commonjs"}。
ts-node -O '{"module":"commonjs"}' src/tools/foo.ts
答案#2
在你的 tsconfig.json 中添加 ts-node 属性。例如如下:
{
"ts-node": { // ts-node automated configuration using commonjs
"compilerOptions": {
"module": "CommonJS"
}
},
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"strictNullChecks": false,
"isolatedModules": false,
"allowUnreachableCode": true,
"noImplicitAny": false,
"noEmit": false,
"outDir": "dist",
"jsx": "react-jsx"
},
"include": ["./src", "./*.json", "./*.ts", "snapshot3.js"],
"typeAcquisition": { "enable": true },
"exclude": ["**/node_modules/**", "**/tmp/**", "**/build/**", "**/dist/**"]
}
然后运行单个 tsx 文件:
ts-node to/single/file.tsx
当你需要一些 ts-node 的选项时,只需修改 tsconfig.json 的 ts-node 属性
或者 在不移除 package.json 中 {"type": "module"} 的情况下,直接使用 ts-node ESM 实验功能
cross-env-shell NODE_ENV=development node --experimental-specifier-resolution=node --loader ts-node/esm -r dotenv/config "src/to/file.ts"
cross-env-shell NODE_ENV=development 是 可选的
