Reputation:
This is a very confusing topic for me at the moment and I believe for a lot of other people too. A lot of the advice that's floating around the internet seems to be very misleading.
I am trying to build a basic web page with just plain TypeScript and HTML. I want to include the compiled JavaScript with a standard <script>
tag such as
<script src="javascriptOutput/myCompiledJsFile.js></script>
while still being able to use normal module functionality of TypeScript, meaning splitting my code up into different files and importing them in the main script myCompiledJsFile.js
that I include in my HTML.
With the following tsconfig.json
,
{
"compilerOptions": {
"target": "es5",
"module": "commonjs"
// ...
}
}
the JavaScript console always throws this error: Uncaught ReferenceError: exports is not defined
.
From what I have read it seems like the problem lies in the module system being specified as commonjs
, which doesn't seem to work without an external module loader (like SystemJS, the one included in Webpack etc.).
I think it should be possible to use TypeScript without one of these external module loaders, if I am right. But I don't know how to configure TypeScript to compile in such a way that browsers can run the compiled code without the Uncaught ReferenceError
. And I also don't know where you can find this information on what browsers support which module loaders / module systems. Do I have to look at the JavaScript engine the browser runs (e.g. V8 for Chrome) ?
I also don't want to work with any 'hacks' like adding var scripts = {}
or the like or removing lines in the compiled JS.
Upvotes: 1
Views: 1400
Reputation:
In case someone is wondering: the solution to my problem was to use the native ES module system. That means choosing either ES2015
or ES2020
for the module
key in the tsconfig.json
, based on what the browser supports. Since I was looking to run my code in Chrome only (Electron) and Chrome fully supports ES2020 as of today, I chose to use ES2020
for my module system.
If you choose to use these modules, AFAIK, you need to add the type="module"
attribute to your script tag:
<script src="../myJsFolder/myJs.js" type="module"></script>
Upvotes: 4