generator-grunt-symfony icon indicating copy to clipboard operation
generator-grunt-symfony copied to clipboard

multipage requirejs

Open MichaelKubovic opened this issue 8 years ago • 2 comments

Currently you bundle all javascript code together with almond into one huge file. Imagine we could easily support more effective packaging by providing some more configuration options.

The approach I'm suggesting allows you to configure bundles (e.g. page specific), then leave r.js trace it's dependencies and leave the rest of code in the common bundle.

In the end you end up having:

  • require.js - module loader needed. no async loads in production however (intentionally)
  • common.js - vendor deps required across the page, requirejs config, default module which handles common parts of the site (think header or what)...
  • page.js - module containing page specific code + vendor deps traced by r.js

_requirejs.html

<script src="{{ asset('vendor/require.js', 'mad') }}"></script>
<script src="{{ asset('js/common.js', 'mad') }}"></script>
{% if app.environment == 'prod' and module %}
    <script src="{{ asset('js/' ~ module ~ '.js', 'mad') }}"></script>
{% endif %}
<script>
    requirejs.config({
        baseUrl: '{{ asset('js', 'mad') }}'
    });

    /**
     * The heart of our require.js setup!
     *
     *   1) Require the common.js file to get all the paths and shim setup
     *   2) Once that file is downloaded, download and execute app/default.js
     *      (a global module, executed on every page) and execute whatever
     *      page-specific app we have (e.g. app/homepage). This will do
     *      whatever craziness we want.
     */
    require(['common'], function (common) {
        {% if module and default is defined and default == false %}
            require(['{{ module }}']);
        {% elseif module %}
            require(['app/default', '{{ module }}']);
        {% else %}
            require(['app/default']);
        {% endif %}
    });
</script>

product.html.twig

{% block requirejs %}
    {{ include('MadnessT3Bundle::_requirejs.html.twig', {
        module: 'app/product'
    }) }}
{% endblock %}

kudos to @weaverryan for an impressive approach he has illustrated in his talk http://www.slideshare.net/weaverryan/cool-like-frontend-developer-grunt-requirejs-bower-and-other-tools-29177248

I will be more than happy to prepare a PR if you find this appropriate for the generator.

MichaelKubovic avatar Sep 24 '15 11:09 MichaelKubovic