I'm starting a new project in which I'd like to have ES6 style modules, however, I can't get it to run in a browser. I'm using Chrome.
I isolated the issue into very few lines of code.
Here are my 2 TypeScript files:
app.ts
import { Component } from './component';
var component: Component = new Component();
component.ts
export class Component {
}
Here's how they compile to JavaScript:
app.js
import { Component } from './component';
var component = new Component();
component.js
export class Component {
}
My index.html only contains a script tag. I tried a few variations, but none of them worked.
index.html #1
<script src="src/app.js" type="module"></script>
The script is not loaded. (No request in network tab)
index.html #2
<script src="src/app.js" type=module></script>
The script is not loaded. (No request in network tab)
index.html #3
<script src="src/app.js"></script>
Uncaught SyntaxError: Unexpected token {
I'm using tsc to transpile TypeScript via Visual Studio Code.
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "silent"
}
}
]
}
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"sourceMap": false,
"removeComments": false,
"noImplicitReturns": true,
"noImplicitAny": true,
"preserveConstEnums": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"outDir": "../src/"
},
"exclude": [
"logs",
"node_modules"
]
}
<script type=‘module’ src=‘thing.js’>
– Ianianaapp.js
change yourimport
statement to the following:import { Component } from './component.js';
Note: the file extension.js
has been added to the Module Specifier. The ECMA-262 Imports Syntax only defines the syntax for modules and not the specific mechanism(s) for loading them. So the requirement for with or without a.js
suffix may vary per implementation. However the inclusion of.js
file extension is required in Safari browser, and most probably in Chrome too. Also, utilize<script src="src/app.js" type="module"></script>
in index.html – Lateritious.mjs
file extension in the Module Specifier too (as noted here), however the.mjs
file extension does not work with the latest Safari browser. – Lateritious