0

I am use grunt-typescript to generate a single js file from a set of ts files. This works fine until I add an import statement to one of the ts files.

Example grunt-typescript config

    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 e.g.

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. The import seems to cause it to compile File2.ts totally separately.

Is this to be expected with import or how can I fix this to create the expected single js file without compile errors?

1 Answer 1

2

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 and single-file compilation are inherently different modes of working and don't like to be mixed. To read up on internal vs external modules check out this TypeScript wiki page.

You technically can still import AMD modules using the standard JavaScript method, but it's awkward. For example, using the require.d.ts file from DefinitelyTyped:

/// <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.

Alternately I would recommend going full 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.