简体   繁体   中英

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. ie 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. ie not behind node, or using systemjs or webpack.

the sample repo is here

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 etc

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

You need to either install angular-cli (by doing npm install -g @angular/cli ) or pass the build you have now through browserify or webpack.

The CLI can be useful for generating a project ( ng new PROJECT_NAME ) that has some useful npm scripts in its package.json .

Edit: didn't read it was about an old version of Angular. The option of using browserify/webpack still stands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM