当前位置: 动力学知识库 > 问答 > 编程问答 >

requirejs - Using r.js to concatenate CSS

问题描述:

I'm working on a project using require.js and plan to optimize it using r.js. The optimization for javascript files is built in as part of the require configration automatically.

What I would like is to split the CSS into several different files, e.g. head.css, body.css, main.css, etc. When r.js runs, it should concatenate these into a single file. The HTML would have:

<link rel=stylesheet type=text/css href=css/main.css>

A problem is that during development, the files will still be split up. I'd like to keep them split and don't want to have to redo the optimization every time -- even if it can be done automatically.

I'd also like to be able to keep the HTML with just the one stylesheet reference even in development. What would be the optimal way to do this?

There are several possibilities that I can see, each with potential problems:

  1. Have main.css use @import to include all other CSS files.

    • Not automatic -- have to edit main.css for each file. That's not a big deal since the number of files will be relatively small and probably all known very early on.
    • r.js does not optimize this
  2. Use require-css

    • This seems to be geared more towards AMD loading of CSS -- I'd rather load all the CSS up front
    • Same issues with automatic loading of CSS files as the other option
  3. Create my own script that calls r.js without CSS optimization, concatenate all of the CSS files and minify appropriately.

    • I'm sure there's someone out there who has done this better than I will

网友答案:

I use grunt-contrib-cssmin which works great. You can also pass arguments to grunt, so you can have grunt:dist combine all your css and plain grunt will leave them separate.

module.exports = function (grunt) {
  grunt.initConfig({
    cssmin: {
      add_banner: {
        options: {
          banner: '/* My minified css file */'
        },
        files: {
          'dist/css/dist.min.css': ["bower_components/bootstrap/dist/css/bootstrap.css", "tmp/css/dist.css"]
        }
      }
    }
  })
}

Grunt getting started.

There is also a requirejs script for grunt. The setup looks like this:

requirejs: {
  compile: {
    options: {
      baseUrl: "path/to/base",
      mainConfigFile: "path/to/config.js",
      out: "path/to/optimized.js"
    }
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: