简体   繁体   English

添加打字稿导入可防止编译为单个js文件

[英]Adding typescript import prevents compiling to a single js file

I am use grunt-typescript to generate a single js file from a set of ts files. 我正在使用grunt-typescript从ts文件集生成单个js文件。 This works fine until I add an import statement to one of the ts files. 在我将导入语句添加到ts文件之一之前,该方法工作正常。

Example grunt-typescript config 示例grunt-typescript配置

    typescript: {
        server: {
            src: ["./ts/file1.ts", "./ts/file2.ts"],
            dest: "./js/out.js",
            options: {
                module: 'amd', //or commonjs
                target: 'es5', //or es3
                basePath: '',
                sourcemap: false,
                declaration: false,
                ignoreError: false
            }
        }
    }

If I add an import statement to the top of file2.ts eg 如果我将导入语句添加到file2.ts的顶部,例如

import PG = require("pg");

Then I get errors that code in File1.ts can't find types defined in File2.ts and I get an unexpected File2.js generated in the /ts directory ignoring the dest file parameter. 然后,我收到错误消息,指出File1.ts中的代码找不到File2.ts中定义的类型,并且在/ ts目录中生成了意外的File2.js,忽略了dest file参数。 The import seems to cause it to compile File2.ts totally separately. 导入似乎导致它完全单独编译File2.ts。

Is this to be expected with import or how can I fix this to create the expected single js file without compile errors? 这是导入所期望的还是我如何解决此问题以创建期望的单个js文件而没有编译错误?

As soon as you import an AMD module, or export from outside of any internal module, your file will be compiled as an AMD module. 导入AMD模块或从任何内部模块外部导出后,文件将被编译为AMD模块。 AMD and single-file compilation are inherently different modes of working and don't like to be mixed. AMD和单文件编译本质上是不同的工作模式,并且不喜欢混合使用。 To read up on internal vs external modules check out this TypeScript wiki page . 要阅读内部和外部模块,请查看此TypeScript Wiki页面

You technically can still import AMD modules using the standard JavaScript method, but it's awkward. 从技术上讲,您仍然可以使用标准JavaScript方法导入AMD模块,但这很尴尬。 For example, using the require.d.ts file from DefinitelyTyped: 例如,使用DefinitelyTyped中的require.d.ts文件:

/// <reference path="require.d.ts"/>

require(["somemodule"], (SomeModule: namespace.SomeModule) => {
    // async code called after the module is retrieved
});

Without the import keyword TypeScript does nothing about the require and leaves you on your own. 如果没有import关键字,TypeScript不会对需求做任何事情,而是由您自己决定。

Alternately I would recommend going full AMD. 或者,我建议使用完整的AMD。 If any of your libraries are AMD it's easier to work with, and you can still compile down to a single file when it's time to release. 如果您的任何库都是AMD,则使用起来会更容易,并且在发布时仍可以编译成单个文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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