Search code examples
javascripttypescriptsystemjsjspm

SystemJs with TypeScript simple example fails


I'm trying to use SystemJs with TypeScript, based on this article: http://david-barreto.com/how-to-use-typescript-with-systemjs/

index.html

<!DOCTYPE html>
<script src="node_modules/systemjs/dist/system.js"></script>
<script src="node_modules/typescript/lib/typescript.js"></script>
<script>
  System.config({
    transpiler: 'typescript'
  });
  System.import('src/main.ts');
</script>

main.ts

function plusOne(num: number) {
  return num+1;
}

alert(plusOne(1))

However, when oppening index.html in Chrome, I see the following error, Indicating that no transpilation happened:

common.js:85 Uncaught (in promise) Error: Unexpected token :
  Evaluating http://localhost:8080/src/main.ts
  Loading src/main.ts
    ...

What is the problem?


Solution

  • The error happens because SystemJS does not use typescript to transpile the source code in main.ts, because it does not detect that the code needs to be transpiled - it does not contain es6 features like export or import that SystemJS checks for.

    That's the way transpiler option works. You want to set transpiler: 'typescript' to use it for typescript code, but SystemJS is set up to use it for transpiling es6 to javascript, there is no explicit support for typescript and if the code does not look like es6 the transpiler will not be used.

    So you need to explicitly tell SystemJS that your code is es6. Here is SystemJS config that works with your example and SystemJS 0.19. Note that it does not work with the 0.20 version of SystemJS, it seems like you have no other option than to use plugin-typescript.

    <!DOCTYPE html>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script>
      System.config({
        map: {typescript: 'node_modules/typescript'},
        packages: {
          typescript: {main: 'lib/typescript.js', format: 'global'},
          src: {defaultExtension: 'ts', format: 'esm'}
        },
        transpiler: 'typescript',
      });
      System.import('src/main.ts');
    </script>