0

I am a typescript newbie. I don't know how to reference (import) a module in a script

In my index.html file I am referencing

<script src="main.js"></script>

and in the main.ts file I am trying to import another typescrtipt module

import greet from './greeter';
greet();

and in the greeter.ts file I am exporting a function

export default function greet(): void {
  console.log('Hello World');
}

But in the browser console I see an error that says Uncaught ReferenceError: exports is not defined

Here's my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

I tried changing the "module" property to "es2015" but it does not work.

Imtiaz Kabir
  • 119
  • 4
  • 8
  • I think you have first to transpile it. Browser (correct me if i am wrong) cant work with typescript. – Marc Jul 03 '21 at 09:16
  • I transpiled it. If you look closely you will see that I am linking the transpiled `js` files in my html file – Imtiaz Kabir Jul 03 '21 at 10:03
  • Have you tried to set the script type to module? `type="module"`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#aside_%E2%80%94_.mjs_versus_.js See last section: "It is also worth noting that:" & https://stackoverflow.com/a/44591205/5781499 – Marc Jul 03 '21 at 10:07
  • I did not know about it! It does work if you specify `type="module"`. But then any package you install via `npm` or `yarn` can not be imported. It says `Failed to resolve module specifier "". Relative references must start with either "/", "./", or "../".` in the browser console – Imtiaz Kabir Jul 03 '21 at 10:43

1 Answers1

0

Okay, I figured out that I don't need to import that module. I can just add another script tag before the existing script tag which links to the greeter.js

<script src="greeter.js"></script>

and then I do not need to export in greeter.ts or import in main.ts

Imtiaz Kabir
  • 119
  • 4
  • 8