简体   繁体   中英

Require.js something not clear

I am trying to use requirejs and to load external vendor js and to hide global variables like Backbone or Underscore.

Here's my code:

<script data-main="./main" src="<?php echo $rootRequirejs?>/require.js"></script>
<script type="text/javascript">
    require.config({
        baseUrl: "/web/js",
        paths: {
            "jquery": "/vendor/js/jquery-1.7.1.min",
            'underscore': '/vendor/js/underscore-min',
            'backbone': '/vendor/js/backbone-min'
        }
    });

Here's my questions:

1) If I go to the javascript console and I write Backbone or underscore they are defined….
I think it should be not accessible from the console but just from my main.js file.
Why they are global?

these will be global by default due to the way the libraries themselves (backbone, etc) are written - they explicitly use the global space (b/c well, that's how js works). have you tried the AMD-forks of these libs?

maybe a better option as noted by Florian in comments above is to use Require2.0 as it now ships with a "shim" feature which helps you work with non-AMD libs... though i'm not sure that will eliminate the globals.

fwiw, unless you have specific reasons to avoid the globals, they usually aren't that big of a deal.

You can use amd versions of those libraries that are wrapped into AMD modules, that should avoid the use of global variables:

https://github.com/amdjs/backbone

https://github.com/amdjs/underscore

They are maintained by James Burke, the author of RequireJS.

Hope this solves your problem!

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