最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typescript compile outputting "import" when targeting ES5 - Stack Overflow

programmeradmin2浏览0评论

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 pile errors but when running from a simple html page (no node) i get the following error

Uncaught SyntaxError: Unexpected token import

//tsconfig.json

{
      "pilerOptions": {
        "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

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 pile errors but when running from a simple html page (no node) i get the following error

Uncaught SyntaxError: Unexpected token import

//tsconfig.json

{
      "pilerOptions": {
        "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

Share Improve this question edited Apr 13, 2017 at 13:11 Tim asked Apr 13, 2017 at 11:41 TimTim 7,44113 gold badges64 silver badges103 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You have specified in your tsconfig.json that you want the TypeScript piler to pile 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 es 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 remend piling 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.

发布评论

评论列表(0)

  1. 暂无评论