简体   繁体   中英

Loading Mustache as AMD module with RequireJS - Mustache is not defined

I'm having trouble loading mustache.js as an AMD module with RequireJS (for use inside a Backbone model). I'm also getting started with TypeScript, and as a result am not totally following the flow of dependencies and declarations!

Starting with app.ts:

require.config({
    paths: {'jquery': 'lib/jquery-1.8.3.min', 'underscore': 'lib/underscore.min', 'backbone': 'lib/backbone.min', 'mustache': 'lib/mustache', 'appmain': 'AppMain'}, 
    shim: {mustache: { deps: ["jquery"] }, backbone: { deps: ["underscore", "jquery"] }, appmain: {deps: ["backbone", "mustache"] } } });

require(['appmain'], (main) => {
    var appMain = new main.AppMain();
    appMain.run();
});

appmain.ts:

import tm = module("models/TestModel");

export class AppMain {
    public run() {
        var testModel = new tm.TestModel()
    }
}

TestModel.ts:

/// <reference path="../modules/backbone.d.ts"/>
export class TestModel extends Backbone.Model {
    constructor(options?) {
        super(options);
    };
    initialize() {
        var stringTemplate = "{{something}}";
        Mustache.compile(stringTemplate);
    };
}

I get a javascript error saying "Mustache is not defined", although mustache.js does get loaded before TestModel.js. I'm just using the mustache.js from here: https://github.com/janl/mustache.js so I think probably I don't understand how AMD modules are properly declared.

I see there are some "AMD wrappers" as part of this project, but I can't seem to figure out how they're used either.

Mustache does define itself as an AMD module , so it does not need to be shimmed. I don't know TypeScript and how it integrates with RequireJS, but try removing Mustache from your config's shim array.

I don't know TypeScript very well, but the documentation mentions that a compiler option will change the generated javascript from CommonJS to AMD. ( --module amd )

Visual Studio TypeScript Options

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM