无法从 .ts 文件导入模块

编程入门 行业动态 更新时间:2024-10-07 20:34:57

无法从 .ts 文件导入<a href=https://www.elefans.com/category/jswz/34/1771428.html style=模块"/>

无法从 .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'

我尝试过的事情:

  • 添加
    "type":"module"
    到我的 package.json 文件
  • 重命名
    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 文件导入模块

本文发布于:2024-05-30 09:28:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   文件   ts

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!