Context
I have these two TypeScript files:
// something.ts
let x = 3;
export default x;
// index.ts
import x from "./something";
console.log(x);
under these tsconfig.json
settings:
{
...
"target": "es2016",
...
// "module": "commonjs" /* <- commented out */
}
when I compile this into JavaScript, I get these two files (which is what I expect):
// something.js
let x = 3;
export default x;
// index.js
import x from "./something";
console.log(x);
Now, I’ve linked the index.js
file from my HTML file like so:
<script src="./dist/index.js"></script>
Problem
When I try opening this up using Live Server, I get this error in the console:
Uncaught SyntaxError: Cannot use import statement outside a module
So, how do I fix this?
What I’ve tried
- Adding back the
"module": "commonjs"
line in mytsconfig.json
file
This results in a different error message appearing in the console:
Uncaught ReferenceError: exports is not defined
As per this SO post, a suggested solution is to comment out the "module": "commonjs"
line, which essentially throws my situation into an infinite loop…
- Adding
"type": "module"
to the<script>
tag andpackage.json
From this SO post, a suggested solution is to add "type": "module"
to the <script>
tag:
<script type="module" src="./dist/index.js"></script>
but now I get this error message:
GET http://127.0.0.1:5501/dist/something net::ERR_ABORTED 404 (Not Found)
.
In the same post, another suggestion was to add “type”: “module” to the package.json
file:
{
"type": "module",
"dependencies": {
"typescript": "^4.6.2"
}
}
and from what I’ve observed, this doesn’t really do anything.