Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure uglifyjs from package.json

Currently, when developing Wordpress themes I use a simple batch file to uglify my js. An example batch file makebundle.bat

call uglifyjs^
  src/file1.js^
  src/file2.js^
  -cmo bundle.min.js

I then use watch to build it like this

watch makebundle src

All very simple. Now, I'd like to make this a less Windows-specific process. For the reasons outlined here I don't want to use Grunt / Gulp, and was thinking of trying to use npm as a build tool. The only trouble is, I can't find out how to configure uglifyjs from within package.json

edit

Here's an example of something I'd like to work in package.json:

{
  "uglifyConfig": [
    {
      "outfile": "bundle.min.js,
      "files": [
        "src/file1.js",
        "src/file2.js"
      ]
      "config": {
        "mangle": true,
        "compress": true
      }
    }
  ]
}
like image 839
JasonC Avatar asked Jul 21 '15 17:07

JasonC


People also ask

What is Uglify and minify?

Minifying is just removing unnecessary white-space and redundant like comments and semicolons. And it can be reversed back when needed. Uglifying is transforming the code into an "unreadable" form by changing variable names, function names, etc, to hide the original content.

Does Uglify support ES6?

uglify-es is no longer maintained and uglify-js does not support ES6+.


2 Answers

If your build script is a node script, you can use Uglify's JavaScript API instead of the command-line API. You can easily require() your package.json, read configuration from it, and pass those values to Uglify.

package.json:

{
  ...
  "scripts": {
    "ugly": "node do-uglify.js"
  }
  ...
}

do-uglify.js:

var uglify = require('uglify');
var package = require('./package.json');
var uglifyConfig = package.uglifyConfig;
// Call the UglifyJS Javascript API, passing config from uglifyConfig
like image 199
cspotcode Avatar answered Oct 06 '22 00:10

cspotcode


You can put any scripts you want in the "scripts" section of package.json.

{
  "name": "my-package",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "ugly": "uglify",
    "prepublish" : "uglify"
  },
...

You can give it any arbitrary name and run it with npm run ugly or use one of the predefined hooks such as prepublish

like image 24
Gangstead Avatar answered Oct 06 '22 01:10

Gangstead