Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Shim Twitter Bootstrap for RequireJS

The RequireJS docs say that to support older versions of IE, you need to configure enforceDefine: true.

So if you want to support Internet Explorer, catch load errors, and have modular code either through direct define() calls or shim config, always set enforceDefine to be true. See the next section for an example.

NOTE: If you do set enforceDefine: true, and you use data-main="" to load your main JS module, then that main JS module must call define() instead of require() to load the code it needs. The main JS module can still call require/requirejs to set config values, but for loading modules it should use define().

Since Twitter Bootstrap isn't an AMD module, I need to shim it for it to work. This is how I configure it;

<script type="text/javascript">
    var require = {
        paths: {
            "bootstrap": "../bootstrap",
            "jquery": "../jquery-1.8.2"
        },
        shim: {
            "bootstrap": ["jquery"]
        },
        enforceDefine: true
    };
</script>

Later when my module wants bootstrap as a dependency, I still end up with an error message;

Error: No define call for bootstrap

http://requirejs.org/docs/errors.html#nodefine

If I've understood the docs correctly, enforceDefineshould ignore shims but it's not.

What am I doing wrong here?

question from:https://stackoverflow.com/questions/13377373/shim-twitter-bootstrap-for-requirejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the docs that error is thrown if "Script was part of a shim config that specified a global string property that can be checked for loading, and that check failed."

To fix this you need to add exports value in the shim config so that RequireJS can check whether the script was succesfully loaded. In case of Bootstrap that's slightly tricky as Bootstrap doesn't 'export' a propert global variable only a bunch of jquery plugins, but you can use any of those plugins as an export value e.g. $.fn.popover:

{
    paths: {
        "bootstrap": "../bootstrap",
        "jquery": "../jquery-1.8.2"
    },
    shim: {
        "bootstrap": {
          deps: ["jquery"],
          exports: "$.fn.popover"
        }
    },
    enforceDefine: true
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...