Fixing error “TypeError: define is not a function” with TypeScript

If you try to run TypeScript programs on the command line (or tests) you can get this irritating and cryptic error:

TypeError: define is not a function

Typically this comes with a very large stack trace.

What this actually means is that your files aren’t being compiled into the correct module format. You want this, in tsconfig.json (if you don’t have one, you can do “tsc –init”).

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "dist"
    },
    "exclude": [
        "node_modules",
        "typings"
    ]
}

The key here is to switch to commonjs.

Note also that I’ve added outDir – this puts all the compiled Javascript in a separate folder, where it’s easier to delete and look at. If you take this verbatim, you’ll want to delete the old Javascript files you made with tsc, or things will get confusing.

Leave a Reply

Your email address will not be published. Required fields are marked *