nikitablack
nikitablack

Reputation: 4663

Why can't amd loader load a script?

I'm trying to make a module code work. So far I have the following code:

// third_party/test/Test.ts
export function test():void
{
    console.log("QWERTY");
}

// Main.ts
// import {test} from "./third_party/test/Test"
require([], function () {
    console.log("Loaded");
}

// index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <script data-main="build/library" type="text/javascript" src="scripts/third_party/require/require.js"></script>
    </head>
</html>

// tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "module": "amd",
        "sourceMap": true,
        "outFile": "build/library.js"
    }
}

Please note the commented import statement in Main.ts. This code works as expected - I can see the output message. But as soon as I uncomment import in Main.ts I don't see anything. There're no errors or warnings.

Since I'm using outFile compiler option I have only one js file.

Upvotes: 0

Views: 192

Answers (1)

Louis
Louis

Reputation: 151390

The file produced by your compilation contains modules defined like this:

define("third_party/test/Test", ["require", "exports"], function (require, exports) {
// ...
define("Main", ["require", "exports"], function (require, exports) {
// ...

Note the first argument to define. These are the names under which your modules are known to RequireJS. Your data-main requests a module named build/library. There's no such module with this name in your bundle.

You need to ask RequireJS to load Main. Here's a simple way to do it:

<!DOCTYPE html>
<html lang="en">
    <head>
      <script type="text/javascript" src="node_modules/requirejs/require.js"></script>
      <script>
        require.config({
          // All modules are under the "build" path.
          baseUrl: "build",
          // The "library" bundle contains the module "Main" so when
          // "Main" is requested, look for it in "library". 
          bundles: {
            "library": ["Main"],
          },
        });
        require(["Main"]);
      </script>
    </head>
</html>

Upvotes: 2

Related Questions