Captain John
Captain John

Reputation: 2001

Loading Bootstrap with AMD Modules and typescript

I'm trying to load Bootstrap using RequireJS and typescript AMD modules.

At present I have the following in my requireJS config:

require.config({
    shim: {
        bootstrap: { deps: ["jquery"] }
    },
    paths: {
        jquery: "//code.jquery.com/jquery-2.1.4.min",
        bootstrap: "//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min",
        d3: "//d3js.org/d3.v3.min"
    }
});

Then in a class I wish to do:

import jq = require("jquery");
import bootStrap = require("bootstrap");

class test {
    public doStuff(): void {
        jq("#test").carousel();
    }
}

Which is compiled by typescript into:

define(["require", "exports", "jquery"], function (require, exports, jq) {
    var testViewModel = (function () {
        function testViewModel() {
        }
        testViewModel.prototype.doStuff = function () {

            jq("#test").carousel();
        };
        return testViewModel;
    })();
})

So the problem seems to be because bootstrap extends jquery and is not actually used directly it's not output into the compiled javascript.

I can just include a reference to bootstrap somewhere in my class to fix the issue but this feels somewhat error prone.

What am I missing?

Upvotes: 3

Views: 2350

Answers (1)

basarat
basarat

Reputation: 276255

The code import bootStrap = require("bootstrap"); will not generate any js unless you use the imported name as a variable. This allows you to do lazy loading and importing type only as documented here.

Fix :

import jq = require("jquery");
import bootStrap = require("bootstrap");
let bs = bootStrap; 

Even better move such code into ui.ts and then import that file everywhere e.g. ui.tsx.

Upvotes: 3

Related Questions