最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法从 .ts 文件导入模块

网站源码admin51浏览0评论

无法从 .ts 文件导入模块

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论