I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the
"module":"ES6"
configuration, but the problem persists.
This is the current setup in my tsconfig.json
:
{
"compilerOptions": {
"module": "es6",
"target": "es6",
"lib": ["es6"],
"sourceMap": true,
}
}
Test Scenario Involving Two Modules:
I created a basic test scenario with two modules.
The first module —
module1.ts
— exports only a constant, like so:-
export const testText = "It works!";
-
The second module —
main.ts
— simply imports the exported constant from the first module:-
import { testText } from 'module1'; alert(testText);
-
The resulting file for the second module (or main.js) is included in my index.html
file, with the type attribute set as type="module"
in the <script ...>
tag, which looks like this:
<script src="main.js" type="module"></script>
Testing this setup in Firefox (dom.moduleScripts.enabled
enabled) or Chrome Canary (Experimental Web Platform flag enabled) does not yield the expected results.
It appears that the Typescript compiler transpiles the TS
import { testText } from 'module1';
statement into the JS equivalent import { testText } from 'module1';
. (Both are identical)
The correct ES6 import statement should be:
import { testText } from 'module1.js';
(Note the .js extension)
Adding the file extension manually to the generated code makes it work as intended.
Have I made an error in my settings or is there an issue with the Typescript
"module": "es6"
configuration? Is there a way to configure tsc to automatically add .js file extensions to generated import statements?