Search code examples
javascripttypescriptes6-modules

Proper way to import functions from other file in TypeScript


I have few functions in functions.ts file, like this:

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

and in the end of file, I export these functions:

export {fun1, fun2, fun3};

In the index.ts file, that is called in html (it's very simple client-side app), I import these functions:

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

When I run it in the browser (of course after npx tsc ) I get Uncaught SyntaxError: Cannot use import statement outside a module, pointing on the import statement in index.js file

I tried to change few lines inside package.json and tsconfig.json, according to the answers in similar questions.

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. */
  }
}

I tried many configurations of "target", "module" and "type" options in both files, but I get errors, sometimes slightly different.


Solution

  • When you link your script, make sure to have type="module":

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

    Reference: JavaScript Modules: Applying the module to your HTML