Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript compile outputting "import" when targeting ES5

I've started a simple repo to test angularjs 1.6. However i seem to be having issues outputting es5 code, which can run without systemjs, node webpack etc. i.e. converting the exports and define and imports statements

// The following app.ts

import * as angular from 'angular'
import * as ng from 'angular'
"use strict";

module ngTypescript{
    angular.module('ngTypescript',[]).run(($rootScope:ng.IRootScopeService) =>{
        console.log($rootScope.$id);         
    });
}

//outputs app.js

import * as angular from 'angular';
"use strict";
var ngTypescript;
(function (ngTypescript) {
    angular.module('ngTypescript', []).run(function ($rootScope) {
        console.log($rootScope.$id);
    });
})(ngTypescript || (ngTypescript = {}));
//# sourceMappingURL=app.js.map

no compile errors but when running from a simple html page (no node) i get the following error

Uncaught SyntaxError: Unexpected token import

//tsconfig.json

{
      "compilerOptions": {
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "classic",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es6", "dom" ],
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "allowUnreachableCode": true
      },
        "exclude": [
            "node_modules/*"
        ]
    }

I need the outputted js to run in an environment without support for exports or imports. i.e not behind node, or using systemjs or webpack.

the sample repo is here

like image 456
Tim Avatar asked Apr 13 '17 11:04

Tim


People also ask

How do I enable imports in TypeScript?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.

Does TypeScript compile to ES6?

TypeScript is a transpiler. Grunt, Gulp, and Babel are some other transpilers to compile the modules. Therefore, TypeScript supports ES6.

Why does TypeScript compile to JavaScript?

ts files and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all.


1 Answers

You have specified in your tsconfig.json that you want the TypeScript compiler to compile to ES5. This will handle ES6 stuff like arrow functions, generators, string interpolation e.t.c

It will not handle modules though because the module field is still set to ES2015. You need to change it to something like amd, umd or system (for systemjs).

EDIT: Let me clarify what those module systems are more. The need for a module system in JavaScript comes from the fact that JavaScript was built for the browser. In the early days you could just include multiple JavaScript files using script tags:

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

But this is inefficient for larger applications. When JavaScript made the move to the server with NodeJS, CommonJS was born. It looks like this:

//Anything above this line is run once, when the project initializes
module.exports = {//your module here}

CommonJS is still used with NodeJS but it's not so popular with the frontend applications because it's synchronous and that does not match the asynchronous nature of the browser. (When in the server you don't have to make an XHR to fetch the file, it's right there in the filesystem but that's almost always not true for the browser).

To satisfy that need, AMD or Asynchronous Module Definition was born. It looks like this:

define(['jquery', 'lodash', 'moment'], function ($, _, moment) {
    //Define your module here
});

AMD had one downside though, it could not be used with NodeJS without extra overhead. And there are libraries, like moment, that are equally used in the server and on the browser. Thus came UMD, short for Universal Module Definition to establish a unified interface for module definitions.

As of 2019, the official standarization of ES2015 modules seems to be gaining ground while CommonJS isn't going away any time soon. As far as TypeScript is concerned, I recommend compiling to CommonJS for server applications and AMD for client side for frontend apps. If you use a framework like Angular, then ES2015 modules are a better option because they allow for tree-shaking and dead code elimination

Check this out. Just search for "module" and you'll see the available options

like image 101
dimlucas Avatar answered Sep 20 '22 13:09

dimlucas