模块"/>
无法从 .ts 文件导入模块
我以前构建过 reactJS 项目,但这次我只需要能够从命令行运行命令,所以我想我会使用节点来完成任务。但是我坚持从其他文件导入函数。
我有这个
main.ts
:
import testFunction from './testFunction.js'
async function main() {
console.log('Node Start Project')
console.log(testFunction('bobby'))
}
(async () => {
await main()
})();
在我的
package.json
中:
{
"name": "testnode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"main": "node main.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"typescript": "^5.0.4"
},
"dependencies": {
"clarifai-nodejs-grpc": "^8.0.0",
"dotenv": "^16.0.3",
"sjcl": "^1.0.8"
}
}
在我的
tsconfig.json
中:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"]
}
我希望能够使用 Typescript。 testFunction 文件包含如下内容:
export default function testFunction(name: string): string {
return 'Hello ' + name
}
但是我不断得到的错误是:
(node:12492) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/bridgeman/Projects/testnode/main.ts:3
import testFunction from './testFunction.js'
我尝试过的事情:
- 添加
到我的 package.json 文件"type":"module"
- 重命名
为main.ts
main.mjs
- 重命名
为testfunction.ts
testfunction.mjs
- 使用
代替require
:import
(这有效,但我不能在我的函数中使用打字稿,我得到错误const testFunction = require('./testfunction.ts')
)SyntaxError: Unexpected token ':' in the function params
请帮忙,我只想导入功能并继续我的项目。
回答如下:第一:
npm install ts-node -D
.
然后:将
"main": "node main.ts"
替换为"main": "ts-node main.ts"
中的package.json
.
更多推荐
无法从 .ts 文件导入模块
发布评论