RequireJS: loading modules, including templates and CSS

After playing with AMD / RequireJS, I was wondering if it's worth loading the user interface modules, including templates and CSS, so they are completely independent of the web page.

Sounds good, but I have not seen how it is implemented in the wild, so there may be pitfalls.

Think of some UI module with the following structure:

myWidget |--img |--main.js |--styles.css +--template.tpl 

All materials in one folder. It looks very good.

The module in main.js will look something like this:

 define(["TemplateEngine", "text!myWidget/template.tpl"], function(TemplateEngine, template) { // Load CSS (Pseudo Code) var cssUrl = "myWidget/styles.css"; appendToHead(cssUrl); return function() { return { render: function(data) { return TemplateEngine.toHtml(template, data); } } } }); 

Now questions:

  • Did I miss something?
  • Are there any plugins / concepts on how to achieve this in a β€œstandard” way?
  • Can the RequireJS optimizer handle the CSS part here, say concat / minify stylesheets, as is done with the JS parts?
  • Any opinions on this? Good or bad?
+68
javascript css requirejs js-amd
Oct 27 '11 at 2:41
source share
2 answers

You can specify the template as a dependency using text! as you showed. I do this using Mustache templates.

However, Require.js does not explicitly support css files.

Here is the official explanation, it explains quite well: http://requirejs.org/docs/faq-advanced.html#css

Edit: February 2012

Templates, such as handlebars, can also be precompiled and included just like any other JS module http://handlebarsjs.com/precompilation.html

Edit: August 2015

If you are after this kind of modulation, you should study webpack and, in particular, css-loader . I use it to join .css files with .jsx files as a single β€œmodule” and extract the corresponding CSS into a single stylesheet during assembly.

+49
Nov 02 2018-11-11T00:
source share

There is a third-party CSS plugin for RequireJS that seems to work well: https://github.com/VIISON/RequireCSS/ .

+6
Sep 22
source share



All Articles