Search code examples
javascripttypescriptrequire

Typescript is compiling import to use require but browser complains


I have set:

<script src="./Snake.js" type="text/javascript"></script>

on my HTML file.

and I have Snake.ts that I am compiling to JS with the following configuration:

{target: "es6", module: "commonjs"} 

but Typescript is converting my import statements to use the require function (which only works with NodeJS) and so the browser complains about

Uncaught ReferenceError: require is not defined.

I am not using require anywhere in my code, but Typescript is automatically converting my import statements to use the require function instead of

import Game from './Game';

I have tried everything, including switching to and, umd, es2020. It was working yesterday.

How do I compile Typescript code to browser JavaScript code and node NodeJS code.


Solution

  • In your configuration you are setting the module system to commonJS, which uses require to import the module.

    Set the module system to ES2015/ES6 in the typescript configuration.

     {target: "ES6", module: "ES2015"}