Asset pipeline for Ember.js, Express.js and Node.js?

后端 未结 3 1253
醉话见心
醉话见心 2021-02-02 18:33

I\'m building an Ember.js application using Express.js as the backend. Right now, I load all my *.js files individually and store my Handlebars templates in my HTML file. I like

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 18:43

    It's possible to build a very convenient system using nothing but connect-assets, grunt-ember-templates and a Gruntfile. First, we need to add the following configuration to Gruntfile.coffee:

    grunt.initConfig
      watch:
        ember_templates:
          files: 'assets/templates/**/*.hbr'
          tasks: 'ember_templates'
      ember_templates:
        compile:
          options:
            templateName: (sourceFile) ->
              sourceFile.replace(/assets\/templates\//, '').replace(/\.hbr$/, '')
          files:
            'assets/js/templates.js': 'assets/templates/**/*.hbr'
    
    # Plugins.
    grunt.loadNpmTasks('grunt-contrib-watch')
    grunt.loadNpmTasks('grunt-ember-templates')
    
    # Default task.
    grunt.registerTask('default', ['ember_templates'])
    

    Then, in our Express.js server configuration:

    app.use require("connect-assets")()
    

    In our index.html file, we need to add two lines in the appropriate places. These need be to processed through the Node.js template engine of our choice:

    <%- css("application") %>
    <%- js("application") %>
    

    We then need to create assets/css/application.styl (which can use @import directives) and assets/js/application.coffee (which can use "#= require foo" comments).

    To use this system, first run:

    grunt
    

    To keep the template.js file permanently up to date, run:

    grunt watch
    

    For everything else, see the connect-assets documentation. Note that I had more luck with Stylus than with Less, which appears to have issues with connect-assets at the time of writing.

    Other tools which are maturing rapidly

    Since I wrote this answer, I've come across several other good options that handle asset compilation in various ways:

    • ember-tools doesn't support CoffeeScript or stylesheets (as far as I can tell), but it handles other asset compilation, and it seems quite popular.
    • brunch.io handles a wide range of asset compilation tasks, including CoffeeScript and various CSS preprocesors. The most promising plugin appears to be brunch-with-ember-reloaded at the moment.

提交回复
热议问题