Spirit Spirit - 1 month ago 18
TypeScript Question

Typescript. KnockoutJs. Uncaught ReferenceError: require is not defined

Currently I am following official ts-ko demo. When I put a direct reference to Ko:

/// <reference path="./node_modules/@types/knockout/index.d.ts" />


There is no errors. But when a refrence is added in the following way:

import * as ko from "knockout";


an error is thrown:


Uncaught ReferenceError: require is not defined


Typescript demo states that:


We’ll need to grab Knockout itself, as well as something called RequireJS.


What is the right way to define RequireJs? Why it is required to use requirejs for "import" case?

package.json

"dependencies": {
"jquery": "3.1.1",
"@types/jquery": "2.0.33",
"knockout": "3.4.0",
"@types/knockout": "1.1.5"
}

Answer

From RequireJs homepage. RequireJS is a JavaScript file and module loader.

What is the right way to define RequireJs?

You can just reference your RequireJs from a script tag.

<script src="scripts/require.js" type="text/javascript"></script>

and define your requireJs configuration.

require.config({
    baseUrl: 'app',
    paths: {
        text: "../scripts/text" //Path to text.js, you will use this to load html that will be used in your ko components,
        widgets: "widgets",
        app: "."
    }
});

Then you can register your component just like this one.

ko.components.register(name, {
    viewModel: { require: path },
    template: { require: 'text!'+ path +'.html' }
});

Why it is required to use requirejs for "import" case?

In order to load your ko components asynchronously, you need a module loader like RequireJs. See this documentation.

Comments