Using Gulp to build requireJS project - gulp-requirejs

前端 未结 7 529
轮回少年
轮回少年 2020-12-12 20:05

I am trying to use gulp-requirejs to build a demo project. I expect result to be a single file with all js dependencies and template included. Here is my gulpfile.js

7条回答
  •  悲哀的现实
    2020-12-12 20:22

    gulp-requirejs has been blacklisted by the gulp folks. They see the RequireJS optimizer as its own build system, incompatible with gulp. I don't know much about that, but I did find an alternative in amd-optimize that worked for me.

    npm install amd-optimize --save-dev
    

    Then in your gulpfile:

    var amdOptimize = require('amd-optimize');
    var concat = require('gulp-concat');
    
    gulp.task('bundle', function ()
    {
        return gulp.src('**/*.js')
            .pipe(amdOptimize('main'))
            .pipe(concat('main-bundle.js'))
            .pipe(gulp.dest('dist'));
    });
    

    The output of amdOptimize is a stream which contains the dependencies of the primary module (main in the above example) in an order that resolves correctly when loaded. These files are then concatenated together via concat into a single file main-bundle.js before being written into the dist folder.

    You could also minify this file and perform other transformations as needed.


    As an aside, in my case I was compiling TypeScript into AMD modules for bundling. Thinking this through further I realized that when bundling everything I don't need the asynchronous loading provided by AMD/RequireJS. I am going to experiment with having TypeScript compile CommonJS modules instead, then bundling them using webpack or browserify, both of which seem to have good support within gulp.

提交回复
热议问题