Frage

I'm using require.js and optimize it with the node module r.js. It works but I have one problem when trying to require a module after I've included require.js.

That's what I need:

<script data-main="/js/app-built" src="/js/vendor/require.min.js"></script>
<script type="text/javascript">
require(['Functions'], function(Functions){
    console.log(Functions);
});
</script>

This doesn't work, as it doesn't find the Functions module. But this works:

<script data-main="/js/app-built" src="/js/vendor/require.min.js"></script>
<script type="text/javascript">
require(['app-built'], function(){
    require(['Functions'], function(Functions){
        console.log(Functions);
    });
});
</script>

Is there a way to achieve the first approach?

War es hilfreich?

Lösung

In your first snippet the problem is that by the time the first require call executes, it is quite possible (quite likely in fact) that RequireJS has not yet loaded your application. The data-main attribute initiates right away the loading of your main module but it only initiates it right away. The loading is still asynchronous. And the reason it works in your second snippet is that the outer require forces the inner require to execute after your main module is loaded.

So for your require call to be successful, RequireJS must have enough information to load it. So it must already have a configuration that will allow it to find your module. This either adding some configuration before you load RequireJS. You can set require to a configuration object which will be picked up by RequireJS when it is loaded:

<script type="text/javascript">
require = {
    // Enough config to find the main module.
    baseUrl: ...,
    paths: ...,
    bundles: {
        // List here every module you want to load individually. 
        "app-built": ["Functions"]
    }
};
</script>
<script src="/js/vendor/require.min.js"></script>
<script type="text/javascript">
require(['app-built']);
require(['Functions'], function(Functions){
    console.log(Functions);
});
</script>

You don't have to pull the whole config out of your main module because RequireJS can combine configs, but there need to be enough there to allow RequireJS to start loading things. The app-built module could contain additional configuration that is not needed for the initial steps. In the code above I've dropped data-main and used require(['app-built']) instead because I'm not sure whether it is possible to still use data-main even when using the bundles parameter. (I'm concerned it might confuse RequireJS.) Using bundles will allow RequireJS to know that when you require Functions, it must find it in app-built.

Apart from perhaps still being able to use data-main instead of the initial require call (which I'm not sure you can do), I do not think it is possible to simplify this further.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top