简体   繁体   中英

Typescript 9.5+; import bootstrap into an AMD module to use jquery extensions

all.

I'm using require.js , and TypeScript in AMD mode, and I'm having trouble importing Bootstrap into my scripts. I've got import statements like this;

import $ = require('jquery');
import ko = require('knockout');
import bootstrap = require('bootstrap');

And it's converting it into this JavaScript;

define(["require", "exports", 'jquery', 'knockout'], 
    function(require, exports, $, ko) {
    ...
});

Notice that Bootstrap isn't in the list of required modules. That's because TypeScript is being 'clever', noting that I'm never referencing the Bootstrap import like this;

// this never appears in my code
bootstrap.blah()

And dropping the 'unused' bootstrap import. In normal cases, this is fine, but bootstrap actually extends jQuery, adding things like

// bootstrap adds jQuery plugins like modal;
$(selector).modal()

So by dropping the include, jQuery is no longer extended with modal() etc, and my code fails.

What I need is a way to tell TypeScript that it really does need to include the 'bootstrap' module in the list of required modules.

Any ideas?

You can make use of this (poorly documented) little trick, by adding the following to the top of your file:

/// <amd-dependecy path="bootstrap">

This will add bootstrap in the list of AMD dependencies.

What you may need is a require.config section, and specify a shim for boostrap.
In this way, both jquery and boostrap export their functions to any $ or jquery selector.

something like :

require.config({
    baseUrl: '../',
    paths: {
        'jquery': 'lib/jquery-1.7.2',
        'boostrap': 'lib/boostrap',
    }, 
    shim: {
        jquery: {
            exports: '$'
        },
        boostrap: {
            exports: '$'
        }
    }
});

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