Uncaught ReferenceError: define is not defined typescript

Here your TypeScript has compiled happily, to code that will work in a requireJS environment (technically, an AMD environment). That means it generates output that assumes that define/require etc all already exist.

The overall answer is that you need to include RequireJS before you depend on your compiled code.

Notably the error suggests you’ve made a separate mistake though: you’re depending directly on the RequireJS module scripts (i.e. you have a <script src="my-compiled-code.js"></script> tag in your HTML). That’s not how require modules work. Instead, once you’ve made RequireJS available, you should have a single top-level startup script (either inline in your HTML or as a separate file) that configures RequireJS and then require()‘s the top-level files of your application to start everything off. You can load this file either by hand, or with RequireJS’s “data-main” attribute.

For example, a minimal HTML looks something like:

<!DOCTYPE html>
<html>
    <head>
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
    </body>
</html>

This loads RequireJS from ‘scripts/require.js’ and then tells it to load the script at ‘scripts/main.js’ to start off the loading process (you’ll probably want to update both paths – note that data-main doesn’t need a .js extension).

The main script should then be something very simple like:

// Set up any config you need (you might not need this)
requirejs.config({
  basePath: "/scripts"
});

// Tell RequireJS to load your main module (and its dependencies)
require("mainmodule");

Generally, it’s not TypeScript problems you’re fighting here, it’s RequireJS. I’d try spending a bit more time playing with just Require (maybe in pure JavaScript, so it’s clearer) and looking at working examples for that, so you can get that bit working first, then add in the rest.

Leave a Comment