Domanda

I'm using r.js to build a production script for my Require JS application and I'm looking for a way to either use an alternate compression library or change the defaults used. I want whitespace to be removed but for variable names to remain the same.

I have a particular requirement to retain variable names as they are and not have them altered. The need for constant variable names introduces a little 'code smell' but it makes the application's configuration file more robust against non-expert editors - so please try to avoid suggesting a design change here.

I currently have r.js configured to not optimise the JavaScript at all, which means not only are variable names retained but also whitespace. The relevant piece from gruntfile.js is provided below.

Can anyone suggest a way to compress whitespace but not change variable names in an r.js build?

  english: {
    options: {
      baseUrl: "js",
      mainConfigFile: "js/app-en.js",
      name: "app-en",
      out: "js/dist/<%= pkg.name %>-en.js",
      optimize: "none"
    }
  }
È stato utile?

Soluzione

The r.js optimizer has settings you can use to control how the minifier operates. The default minifier used is UglifyJS. The uglifyjs option tells r.js how to invoke it. Given the settings you've shown, removing optimize: "none" and adding uglify: { no_mangle: true } is what is needed:

english: {
  options: {
    baseUrl: "js",
    mainConfigFile: "js/app-en.js",
    name: "app-en",
    out: "js/dist/<%= pkg.name %>-en.js",
    uglify: {
      no_mangle: true
    },
  }
}

The whole set of settings that UglifyJS takes is documented here. If you ever need or want to switch to UglifyJS2 or Closure, r.js has uglify2 and closure settings that you can use to set their options.

For Uglify2, the setting to prevent mangling would be:

uglify2: {
  mangle: false
}

With Closure, I believe you'd want:

closure: {
  CompilationLevel: 'WHITESPACE_ONLY',
},
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top