I’ve been pulling my hair with this myself and have found a workable solution. The trick is to use flag --isolatedModules during build.
As an example say that you in your TypeScript project have a main.ts file in your static folder to serve the client (browser) with functionality; src/static/scripts/main.ts.
This is what main.ts file looks like:
const logger = () => {
console.log('Hello browser console!');
};
Having property “type”: “module” set in package.json and building (compiling) your project with tsc will generate the following file dist/static/scripts/main.js:
const logger = () => {
console.log('Hello browser console!');
};
export {};
This won’t work in browser. Building without property “type”: “module” set in package.json will generate the following main.js file:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger = () => {
console.log('Hello browser console!');
};
That doesn't work either in the browser. The trick is to build the main.ts file by itself using the --isolatedModules flag. The rest of the files can be built in normal way.
In package.json make the following build script:
"build": "tsc && tsc --isolatedModules ./src/static/scripts/main.ts --outDir dist/static/scripts"
In tsconfig.json exclude main.ts file from ordinary build:
"exclude": ["node_modules", "dist", "src/static/scripts/main.ts"]
Then run your build script and you will receive this main.js file:
var logger = function () {
console.log(‘Hello browser console!');
};
And voila – it works like a charm in the browser. Hope it helps.
export {};is added to ensure it's still a module, not a script, in JavaScript's eyes. I may be wrong on the latter part though.