Search code examples
gulprequirejsrequirejs-optimizer

requirejs optimizer - how to change the optimized module name


I want to optimize some modules with the requirejs optimizer, but ran into a problem concerning paths. The main.js entry point requires the component on /build/modules/, but the name of the optimized module does not match this path. The component file is loaded, but the function it defines isn't called. main_component.js requires the components moduleA and moduleB, and the build's main.js requires the built main_component.js.

Code of ./build/main.js:

require(['./modules/main_component'], function () {
  console.log('main')
})

Code of ./build/modules/main_component:

/* component definitions ... */
define('main_component',
    ['require','components/moduleA','components/moduleB'],
    function (require) { /* ... */}
)

Project structure:

/
|-- build
|   |-- modules
|   |   +-- main_component.js # optimized file
|   +-- main.js
|-- js
|   +-- modules
|       |-- components
|       |   |-- moduleA.js
|       |   +-- moduleB.js
|       +-- main_component.js
+-- index.html

Also, I'm using a gulp wrapper gulp-requirejs-optimize. This is my gulpfile:

var gulp = require('gulp')
var requirejsOptimize = require('gulp-requirejs-optimize')

gulp.task('default', function () {
  return gulp.src('js/modules/*.js')
    .pipe(requirejsOptimize({
      optimize: 'none'
    }))
    .pipe(gulp.dest('build/modules'))
})

Solution

  • Adding skipDirOptimize: true to the requirejsOptimize options did the trick. As per the docs:

    If doing a whole project optimization, but only want to minify the build layers specified in modules options and not the rest of the JS files in the build output directory, you can set skipDirOptimize to true.