在TypeScript中从其他文件导入函数的正确方法

pcww981p  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(181)

我在functions.ts文件中有几个函数,如下所示:

function fun1(input: string): boolean {
{...}
}

在文件的末尾,我导出了这些函数:

export {fun1, fun2, fun3};

在index.ts文件中,它在html中调用(这是一个非常简单的客户端应用程序),我导入以下函数:

import {isInputValid, receiveExchangeValueFromAPI, convertCurrency} from "./functions";

当我在浏览器中运行它时(当然是在npx tsc之后),我得到Uncaught SyntaxError: Cannot use import statement outside a module,指向index.js文件中的import语句
根据类似问题的答案,我尝试更改package.json和tsconfig.json中的几行。
package.json:

{
  "devDependencies": {
    "@types/jest": "^29.4.0",
    "jest": "^29.4.3",
    "jest-environment-jsdom": "^29.4.3",
    "ts-jest": "^29.0.5",
    "typescript": "^4.9.5"
  },
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "jsdom": "^21.1.0"
  },
  "type": "module"
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "es2020",
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

我在两个文件中尝试了许多“目标”、“模块”和“类型”选项的配置,但我得到了错误,有时略有不同。

krcsximq

krcsximq1#

链接脚本时,请确保type="module"

<script type="module" src="./path/to/my/transpiled/javascript.js"></script>

参考:JavaScript模块:将模块应用于HTML

相关问题