Open MichaelKubovic opened 8 years ago
@MichaelKubovic this looks promising.
Just to share a different implementation I am using the on my project.
So I have a base twig template with the following:
{% if app.environment == 'node' %}
{% block javascriptsDev %}
<script type="text/javascript" src="{{ asset('requirejs-config/config.js') }}"></script>
<script type="text/javascript" data-main={% block javascriptDataMain %}"{{ asset('scripts/page.js') }}"{% endblock %}
src="/bower_components/requirejs/require.js"></script>
{% endblock %}
{% else %}
{% block javascriptsDist %} <script type="text/javascript" src="{{ asset('scripts/page.js') }}"></script>{% endblock %}
{% endif %}
where page.js
would be the page specific JS file.
Then the child template for the specific page would have:
{% block javascriptDataMain %}
"{{asset('scripts/page-customized.js') }}"
{% endblock %}
{% block javascriptsDist %}
<script type="text/javascript" src="{{ asset('scripts/page-customized.js') }}"></script>
{% endblock %}
Now, the page-customized.js
:
require([ 'modules/common-scripts', 'jquery', 'other' ], function(common, jquery, other) {
'use strict';
common.init();
var $ = jquery;
/** Rest of the code goes here **/
});
In the above file modules/common-scripts
is the JS common across the site for all pages.
This requires some changes to the requirejs
grunt task as well. Basically, we need to process each of the customized files too. Here is the updated file
'use strict';
module.exports = function(grunt, options) {
var files = grunt.file.expand(options.paths.app+'/scripts/*.js');
var requirejsOptions = {};
files.forEach(function(file) {
var filename = file.split('/').pop();
requirejsOptions[filename.split('.')[0]] = {
options: {
baseUrl: 'bower_components',
name: 'almond/almond',
include: 'appScripts/'+filename.split('.')[0],
out: options.paths.dist+'/scripts/'+filename,
mainConfigFile: options.paths.app+'/requirejs-config/config.js',
preserveLicenseComments: false,
useStrict: true,
wrap: true,
optimize: 'uglify2',
generateSourceMaps: false,
}
};
});
return requirejsOptions;
};
All my page specific JS file are in app/Resources/public/scripts/
directory.
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:
_requirejs.html
product.html.twig
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.