yeoman / generator-backbone

Scaffold out a Backbone.js project
http://yeoman.io
638 stars 157 forks source link

Templates on RequireJS build are not working #367

Closed tconroy closed 8 years ago

tconroy commented 9 years ago

Hey, I'm curious how I can modify this grunt build script so that all (custom) files are concatenated into a single script. I'm not using RequireJS for the lazy loading but rather for modularization and easy dependency management so I don't really want my release users to require requireJS.

I've attempted to modify my gruntfile to accomplish what I want, but right now I keep running into an issue where the templates.js file is being created in /.tmp/scripts/, but is then is aparrently wiped out / over written by some task which runs after the jst task. Any ideas/help?

Here's my Gruntfile.js:

'use strict';
var LIVERELOAD_PORT = 35729;
var SERVER_PORT = 9000;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
    return connect.static(require('path').resolve(dir));
};

module.exports = function (grunt) {

    require('time-grunt')(grunt);
    require('load-grunt-tasks')(grunt);

    // configurable paths
    var yeomanConfig = {
        app: 'app',
        dist: 'dist'
    };

    grunt.initConfig({
        yeoman: yeomanConfig,
        watch: {
            options: {
                nospawn: true,
                livereload: LIVERELOAD_PORT
            },
            livereload: {
                options: {
                    livereload: grunt.option('livereloadport') || LIVERELOAD_PORT
                },
                files: [
                    '<%= yeoman.app %>/*.html',
                    '{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
                    '<%= yeoman.app %>/scripts/templates/*.{ejs,mustache,hbs}',
                    'test/spec/**/*.js'
                ]
            },
            jst: {
                files: [
                    '<%= yeoman.app %>/scripts/templates/*.ejs'
                ],
                tasks: ['jst']
            },
            test: {
                files: ['<%= yeoman.app %>/scripts/{,*/}*.js', 'test/spec/**/*.js'],
                tasks: ['test:true']
            }
        },
        connect: {
            options: {
                port: grunt.option('port') || SERVER_PORT,
                // change this to '0.0.0.0' to access the server from outside
                hostname: 'localhost',
                livereload: 35729
            },
            livereload: {
                options: {
                    base: [
                        '.tmp',
                        '<%= yeoman.app %>'
                    ],
                    middleware: function (connect) {
                        return [
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, yeomanConfig.app)
                        ];
                    },
                }
            },
            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, 'test'),
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, yeomanConfig.app)
                        ];
                    }
                }
            },
            dist: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, yeomanConfig.dist)
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                path: 'http://localhost:9000'
            },
            test: {
                path: 'http://localhost:<%= connect.test.options.port %>'
            }
        },
        clean: {
            dist: ['.tmp', '<%= yeoman.dist %>/*'],
            server: '.tmp'
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: [
                'Gruntfile.js',
                '<%= yeoman.app %>/scripts/{,*/}*.js',
                '!<%= yeoman.app %>/scripts/vendor/*',
                'test/spec/{,*/}*.js'
            ]
        },
        mocha: {
            all: {
                options: {
                    run: true,
                    urls: ['http://localhost:<%= connect.test.options.port %>/index.html']
                }
            }
        },
        requirejs: {
            dist: {
                // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
                options: {
                    /*added:*/
                    wrap: true,
                    almond: true,
                    replaceRequireScript: [{
                        files: ['<%= yeoman.dist %>/index.html'],
                        module: 'main'
                    }],
                    modules: [{name: 'main'}],
                    baseUrl: '<%= yeoman.app %>/scripts',
                    mainConfigFile: '<%= yeoman.app %>/scripts/main.js',
                    dir: '.tmp/scripts',
                    optimize: 'none',
                    useStrict: true,
                    paths: {
                        'templates': '../../<%= yeoman.app %>/scripts/templates',
                        'jquery': '../../<%= yeoman.app %>/bower_components/jquery/jquery',
                        'underscore': '../../<%= yeoman.app %>/bower_components/lodash/dist/lodash',
                        'backbone': '../../<%= yeoman.app %>/bower_components/backbone/backbone'
                    }
                    /*end added*/

                    /*
                    baseUrl: '<%= yeoman.app %>/scripts',
                    optimize: 'none',
                    paths: {
                        'templates': '../../.tmp/scripts/templates',
                        'jquery': '../../<%= yeoman.app %>/bower_components/jquery/dist/jquery',
                        'underscore': '../../<%= yeoman.app %>/bower_components/lodash/dist/lodash',
                        'backbone': '../../<%= yeoman.app %>/bower_components/backbone/backbone'
                    },
                    preserveLicenseComments: false,
                    useStrict: true,
                    wrap: true
                    */
                }
            }
        },
        /*added:*/
        uglify: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/scripts/main.js': [
                        '.tmp/scripts/main.js'
                    ]
                }
            }
        },/*end added*/

        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>'
            }
        },
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                dirs: ['<%= yeoman.dist %>']
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },
        cssmin: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/styles/main.css': [
                        '.tmp/styles/{,*/}*.css',
                        '<%= yeoman.app %>/styles/{,*/}*.css'
                    ]
                }
            }
        },
        htmlmin: {
            dist: {
                options: {
                    /*removeCommentsFromCDATA: true,
                    // https://github.com/yeoman/grunt-usemin/issues/44
                    //collapseWhitespace: true,
                    collapseBooleanAttributes: true,
                    removeAttributeQuotes: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeOptionalTags: true*/
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: '*.html',
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,txt}',
                        'images/{,*/}*.{webp,gif}',
                        'styles/fonts/{,*/}*.*',
                    ]
                }, {
                    src: 'node_modules/apache-server-configs/dist/.htaccess',
                    dest: '<%= yeoman.dist %>/.htaccess'
                }]
            }
        },
        bower: {
            all: {
                rjsConfig: '<%= yeoman.app %>/scripts/main.js'
            }
        },
        jst: {
            options: {
                amd: true
            },
            compile: {
                files: {
                    // '.tmp/scripts/templates.js': ['<%= yeoman.app %>/scripts/templates/*.ejs']
                    '.tmp/scripts/templates.js': ['<%= yeoman.app %>/scripts/templates/*.ejs']
                }
            }
        },
        rev: {
            dist: {
                files: {
                    src: [
                        '<%= yeoman.dist %>/scripts/{,*/}*.js',
                        '<%= yeoman.dist %>/styles/{,*/}*.css',
                        '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
                        '/styles/fonts/{,*/}*.*',
                    ]
                }
            }
        }
    });

    grunt.registerTask('createDefaultTemplate', function () {
        grunt.file.write('.tmp/scripts/templates.js', 'this.JST = this.JST || {};');
    });

    grunt.registerTask('server', function (target) {
        grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
        grunt.task.run(['serve' + (target ? ':' + target : '')]);
    });

    grunt.registerTask('serve', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'open:server', 'connect:dist:keepalive']);
        }

        if (target === 'test') {
            return grunt.task.run([
                'clean:server',
                'createDefaultTemplate',
                'jst',
                'connect:test',
                'open:test',
                'watch'
            ]);
        }

        grunt.task.run([
            'clean:server',
            'createDefaultTemplate',
            'jst',
            'connect:livereload',
            'open:server',
            'watch'
        ]);
    });

    grunt.registerTask('test', function (isConnected) {
        isConnected = Boolean(isConnected);
        var testTasks = [
                'clean:server',
                'createDefaultTemplate',
                'jst',
                'connect:test',
                'mocha',
            ];

        if(!isConnected) {
            return grunt.task.run(testTasks);
        } else {
            // already connected so not going to connect again, remove the connect:test task
            testTasks.splice(testTasks.indexOf('connect:test'), 1);
            return grunt.task.run(testTasks);
        }
    });

    grunt.registerTask('build', [
        'clean:dist',
        'createDefaultTemplate',
        'jst',
        'useminPrepare',
        'imagemin',
        'htmlmin',
        'concat',
        'cssmin',
        'uglify:generated',
        'copy',
        'requirejs',
        'uglify:dist',
        'rev',
        'usemin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'test',
        'build'
    ]);
};
Inateno commented 9 years ago

Hi, I'm new to bower and yeoman so not maybe my conf will not work.

Here is a project where I'm using requireJS with r.js compilation (aka concatenation + uglification). https://github.com/Inateno/Dreamengine/blob/master/Gruntfile.js

Hope this help

marian-r commented 9 years ago

See #372

ruyadorno commented 9 years ago

Unfortunately this issue persists even after #372 landed on master :disappointed:

Steps to reproduce:

  1. Generate a new project using RequireJS
  2. Creates a new View/template, something in the likes of yo backbone:all Foo
  3. Uses the View/template, simply adding the View to main.js and instantiating it will do
  4. Runs grunt build <- :boom:
sun-ks commented 8 years ago

I have this problem too! =( Please help

sun-ks commented 8 years ago

In Gruntfile js requirejs: { dist: { // Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js options: { almond: true,

      replaceRequireScript: [{
        files: ['<%= yeoman.dist %>/index.html'],
        module: 'main'
      }],

      //modules: [{name: 'main'}],

      baseUrl: '<%= yeoman.app %>/scripts',

      mainConfigFile: '<%= yeoman.app %>/scripts/main.js', // contains path specifications and nothing else important with respect to config
      dir: '.tmp/scripts',

      optimize: 'none', // optimize by uglify task
      useStrict: false,
      wrap: true

    }
  }
},</code>

if you disable line - modules: [{name: 'main'}] - Build succeeds! But i have error in dist/index.html - require is not defined

marian-r commented 8 years ago

I will try to look at it during the weekend.

ruyadorno commented 8 years ago

@marian-r that would be amazing 😊

marian-r commented 8 years ago

Sorry for the delay. I didn't managed to look at it over the weekend, so I will give it a try over the next one. Sorry.

AleeRojas commented 8 years ago

+1

marian-r commented 8 years ago

Fix submitted in #384. After a bit of investigating, the fix was fairly easy. And sorry for the delay.

ruyadorno commented 8 years ago

:confetti_ball: many thanks @marian-r for fixing it!

I'll publish a new patch release soon.

ruyadorno commented 8 years ago

Landed on v0.4.2