首页 文章

typescript编译在定位ES5时输出“import”

提问于
浏览
2

我开始用一个简单的回购来测试 angularjs 1.6 . 但是我似乎有输出es5代码的问题,可以在没有systemjs,节点webpack等的情况下运行,即转换导出和定义和导入语句

//以下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);         
    });
}

//输出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 但是 when running 来自一个简单的html页面(没有节点)我收到以下错误

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/*"
        ]
    }

我需要输出的js在不支持导出或导入的环境中运行 . 即不在节点后面,或使用systemjs或webpack .

the sample repo is here

2 回答

  • 2

    您已在 tsconfig.json 中指定希望TypeScript编译器编译为ES5 . 这将处理ES6的东西,如箭头函数,生成器,字符串插值e.t.c.

    它不会处理模块,因为 module 字段仍设置为 ES2015 . 您需要将其更改为 amdumdsystem (对于systemjs) .

    EDIT :让我澄清一下这些模块系统是什么 . JavaScript中模块系统的需求源于JavaScript是为浏览器构建的 . 在早期,您可以使用脚本标记包含多个JavaScript文件:

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

    但这对于大型应用来说效率低下 . 当JavaScript使用NodeJS迁移到服务器时,CommonJS诞生了 . 它看起来像这样:

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

    CommonJS仍然与NodeJS一起使用,但它并不像前端应用程序那么受欢迎,因为它是同步的,并且与浏览器的异步性质不匹配 . (在服务器中,您不必创建XHR来获取文件,它就在文件系统中,但对于浏览器来说几乎总是如此) .

    为满足这一需求,AMD或异步模块定义诞生了 . 它看起来像这样:

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

    AMD有一个缺点,它不能与NodeJS一起使用而没有额外的开销 . 并且有一些库,如片刻,在服务器和浏览器中同样使用 . 因此,UMD是通用模块定义的缩写,用于为模块定义 Build 统一的接口 .

    截至2019年,ES2015模块的官方标准化似乎正在取得进展,而CommonJS不会很快消失 . 就TypeScript而言,我建议为服务器应用程序编译CommonJS,为前端应用程序编译AMD用于客户端 . 如果您使用像Angular这样的框架,那么ES2015模块是更好的选择,因为它们允许树木抖动和死代码消除

    检查this . 只需搜索"module",您就会看到可用的选项

  • 0

    您需要安装angular-cli(通过执行npm install -g @ angular / cli)或通过browserify或webpack传递您现在拥有的构建 .

    CLI可用于生成在其package.json中具有一些有用的npm脚本的项目(新的PROJECT_NAME) .

    编辑:没看过它是关于Angular的旧版本 . 使用browserify / webpack的选项仍然存在 .

相关问题