Git Product home page Git Product logo

node-minify's Introduction

node-minify

A very light minifier Node.js module.


Build Status

Features

It allow you to compress JavaScript, CSS and HTML files.

JavaScript:

CSS:

HTML:

Command Line Interface:

Installation

npm install @node-minify/core
# Or Yarn
yarn add @node-minify/core
# Or pnpm
pnpm add @node-minify/core

And install the compressor you want

npm install @node-minify/uglify-js
# Or Yarn
yarn add @node-minify/uglify-js
# Or pnpm
pnpm add @node-minify/uglify-js

Quick Start

import minify from '@node-minify/core';
import gcc from '@node-minify/google-closure-compiler';
import uglifyjs from '@node-minify/uglify-js';

// Using Google Closure Compiler
minify({
  compressor: gcc,
  input: 'foo.js',
  output: 'bar.js',
  callback: function (err, min) {}
});

// Using UglifyJS
minify({
  compressor: uglifyjs,
  input: './**/*.js',
  output: 'bar.js',
  callback: function (err, min) {}
});

// Using Promise
var promise = minify({
  compressor: uglifyjs,
  input: './**/*.js',
  output: 'bar.js'
});

promise.then(function (min) {});

// Async/Await
async function doMinify() {
  const min = await minify({ compressor: uglifyjs, input: 'foo.js', output: 'bar.js' });
}

In memory

import htmlMinifier from '@node-minify/html-minifier';

const html = `
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
</html>`;

minify({
  compressor: htmlMinifier,
  content: html
}).then(function (min) {
  console.log('html min');
  console.log(min);
});

More examples

Documentation

Visit https://node-minify.2clics.net for full documentation.

License

MIT

node-minify's People

Contributors

alexbardas avatar arnog avatar azure-pipelines[bot] avatar brianberlin avatar chrispecoraro avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dsego avatar dwi2 avatar greenkeeper[bot] avatar greenkeeperio-bot avatar icoloma avatar indatawetrust avatar lumakernel avatar mandarnaik016 avatar mathiasbynens avatar mergify[bot] avatar renovate[bot] avatar sasha0552 avatar sebbo2002 avatar snyk-bot avatar srod avatar stefanoortisi avatar tedgrubb avatar zhangmx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-minify's Issues

Proposition for dev vs. production

I have an idea and am curious to see what others think.

Take this block for example:

new compressor.minify({
  type: 'uglifyjs',
  fileIn: [
    'public/bower_components/angulartics/dist/angulartics.min.js',
    'public/bower_components/angulartics/dist/angulartics-google-analytics.min.js',
    'public/bower_components/angulartics/dist/angulartics-segmentio.min.js'
  ],
  fileOut: 'public/js/scripts.js',
  callback: function(err, min){
    console.log(err);
  }
});

I would like to pass an extra argument to the callback, that will return a string that looks like:

<script src="bower_components/angulartics/dist/angulartics.min.js"></script>
<script src="bower_components/angulartics/dist/angulartics-google-analytics.min.js"></script>
<script src="bower_components/angulartics/dist/angulartics-segmentio.min.js"></script>

That way, when I'm in my .ejs template I can do something like <%= nonMinified => which will inject the premade string if I'm running on development.

Searching for cleancss in wrong directory

Updating from 1.1.0 -> current broke a custom build tool I've been using. It has to do with this line glob syncing from the current working directory. It should be searching for "**/.bin" relative to __dirname. I'm on deadline right now so I can't fix this for you, currently just reverting to 1.1.0.

uglifyjs support on Windows

The current implementation relies on processing of the uglify script header:

!/usr/bin/env node

which Windows won't do, even within a cygwin environment. The uglify script can't be launched via the command as it is currently written.

find a bug in using minify when type is 'uglifyjs'

new compressor.minify({
type: 'uglifyjs',
fileIn: 'public/js/base.js',
fileOut: 'public/js/base-onefile-uglify.js',
callback: function(err, min){
console.log(err);
// console.log(min);
}
});
After do this,why does't remove comment but only compress the code??
//test( does this comment needn't remove?????)
function(){};

How to clean console.log from js by any compressor?

I have googled that UglifyJS2 can clean console.log which is supported by node-minify , and I just don't get how to use these options in node-minify, I know it had options property, seems UglifyJS2 use that option property very differently..

var minifiedCode = uglify.minify(originalSourceCode, {
                fromString : true,
                mangle: {},
                warnings: true,
                compress:{
                    pure_funcs: [ 'console.log' ]
                }
            });
console.log(minifiedCode);

Temp files not deleted

Hi I'm using your module with supervisor and have set up my server to recompile all my js and css when the server reboots due to a file change.

Problem is that your code seems to spit out a lot of temp files and not cleaning them up.

Is there any way you can add a simple -cleanup style parameter to the options so these can be deleted automatically?

Thanks 💃

Summary of my modifications

Hi, I forked your repository and made various modifications. Since the result was not API-compatible with your repository, I made no pull requests and instead published as abridge on NPM.

However, your users may benefit from some of the API changes.

Thanks for your work

Jquery 2.0.0 Compilation errors

I'm using Google Closure Compiler to compress jQuery2.0.0, anyhow I get the following error message:

ERROR: Command failed: src\javascripts\jquery-2.0.0.js:4051: ERROR - Parse error. missing name after . operator
(jQuery.expr.match.boolean.test(name) ? boolHook : nodeHook);
...

Any solution?

node command not found when running trivial fix suggestion

I think when starting on debian based systems it trys to run node as a shell command to compress/minify when on debain/ubuntu systems the command is nodejs due to a package name clash.

I fixed this by runnning ln -s /usr/bin/nodejs /usr/bin/node on ubuntu. But I thought you might like to add an attempt to try both commands when the module is running.

uglify is not minifying the file

When I do,

// Using UglifyJS for JS
new compressor.minify({
type: 'uglifyjs',
fileIn: 'public/js/base.js',
fileOut: 'public/js/base-onefile-uglify.js',
callback: function(err){
console.log(err);
}
});

It did not minify file. It was able to minimise when I replaced the command in node-minify with following. I have removed quotes around uglifyjs.

            case 'uglifyjs':
                command = prefix  + __dirname + '/../node_modules/uglify-js/bin/uglifyjs --output "' + this.fileOut + '" ' + (this.copyright ? '' : '--no-copyright') + ' "' + this.fileIn + '" ' + this.options.join(' ');

updated to 1.3.0 and getting unexpected token ILLEGAL

I updated to 1.3.0 and now I see below error.

C:\XYZFolder\node_modules.bin\uglifyjs:2
basedir=dirname "$0"
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
] killed: false, code: 8, signal: null }
ui-core compression error: { [Error: Command failed:
C:\XYZFolder\node_modules.bin\sqwish:2
basedir=dirname "$0"
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
] killed: false, code: 8, signal: null }

Conflict between node-minify and cluster modules

If I try to node-js as a cluster, I get intermittent file i/o errors in node-minify. It's kind of odd, because I wait until minify has completed before I start up the cluster via callback. The error I see is:

fs.js:760
return binding.unlink(pathModule._makeLong(path));
^
Error: ENOENT, no such file or directory './tmp/1394491036813'
at Object.fs.unlinkSync (fs.js:760:18)
at /Users/jeff.l/Documents/workspace/maverickUX/node-js/node_modules/node-minify/lib/node-minify.js:104:25
at ChildProcess.exithandler (child_process.js:641:7)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:735:16)
at Socket. (child_process.js:948:11)
at Socket.EventEmitter.emit (events.js:95:17)
at Pipe.close (net.js:466:12)
worker 74524 died

var http = require('http')
    ,cluster = require('cluster')
    ,minify = require('./minify.js') 
;
...
var launchServices = function() {
    var numCPUs = require('os').cpus().length;

    if (isCluster && cluster.isMaster) {
          // Fork workers.
          for (var i = 0; i < numCPUs/2; i++) {
            cluster.fork();
          }

          cluster.on('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died');
          });
    } 
    else {
        var port = parseInt(config['port']);
        server.listen(port);
    }
}

minify({compress: isCompress}, launchServices);

I'm using node-minify 0.9.1, cluster 0.7.7

ENOENT, no such file or directory <PATH/to/FILE>

Hi, I'm having this error a lot using the plugin, it's easy to solve, but it would be great if node-minify could handle this, and create the output file -- including the directory.

Thanks

andvarp

When I use nodemon, it is restarting repeatedly

When I use nodemon, it is restarting repeatedly.
I created ".nodemonignore" file, then i added "/static/minified.js" line in this file.

But nodemon detects node-minify temp file.

EDIT : When i change temp file location, it's corrected.

Not working when using 'no-compress' on large files

I am using the 'no-compress' option to just concatenate an array of files, but for large files it often just return a blank string. It works great if I use any compression method. It looks like the problem is on line 113:

var os = _fs.createWriteStream(this.fileOut);
var is = _fs.createReadStream(this.fileIn);
is.pipe(os);

The pipe function runs asynchronously, so the output file ends up being read and returned before it has finished being written.

use correct npm package for uglify-js

The uglify-js2 npm package should now be installed as uglify-js since it was re-named. The uglify-js2 package is deprecated. At the moment you'll get uglify-js2 for both the dependencies you list.

Minification doesn't support synchronous execution

Hi,

I need to use node-minify in a project, but it only calls asynchronous execution of child processes to do the actual minification work. This is an issue for me, since in my code structure I need it to be done synchronously.

Is it possible to support something like a {sync: true} option, defaulting to false, so that it's run synchronously when the client code requests it?

Missing uglify-js with relative path when already installed as main package dependency

I installed node-minify in a package that already contained minify-js as a dependency, so calling the bin in the relative path to ../node-modules/uglify-js/bin would fail, cause it would live in a different location already

Not sure what the best approach could be for solving this would be - I doubt this is going to be used only in npm scripts, so using devDependencies is probably not a solution, although it would be nice to have a conditional that executes the aliased command when running on npm environment.

cleancss passed more options but not work

hi man , I use clean-css to minify css files and there are some extra options like 'advanced : false' for compatibility , and i see your source code and find you use the CLI to minify the files , but it does work for me , I wonder if there is a way to solve the issues?

Linux support

I've had trying to run minify under Windows .. perfect ... but on Linux (Ubuntu 14.04) it´s not working if i use yui-css, sqwish or uglifyjs. On "no-compress" everything works perfect.

_fs.unlinkSync produces "EPERM, operation not permitted" error.

It seems the _fs.unlinkSync event at line 90 of node-minify.js can throw an EPERM, operation not permitted error. This happens when the no-compress function is used quickly back to back (as in to concatenate a series of folders of files and then combine them after).

This is occurring on Windows 7 64 bit using the latest version of node.

Node.js path error (Windows)

Can you change in "libs/node-minifiy.js" the line:

 var prefix = (platform === 'win32') ? 'node ' : process.argv[0] + ' ';

to

var prefix = (platform === 'win32') ? '"' + process.argv[0].replace(/\\/g,'/') + '" ' : process.argv[0] + ' ';

If node.js is not installed, "node" on cmd can not be found!

Error when type is 'uglifyjs' and fileInput is Array

    new compressor.minify({
     type: 'uglifyjs',
      fileIn: ['file1.js', 'file2.js' ],
      fileOut: 'file.min.js',
      callback: function(err, min){}}
    );

Gives error: 'Path must be a string', seems to originate from the following code in node-minify line 29

     if (typeof options.fileIn === 'object' && options.fileIn instanceof Array &&         options.type !== 'gcc') {
                var out = options.fileIn.map(function(path) {
                    return _fs.readFileSync(path, 'utf8');
                });

        _fs.writeFileSync(this.tempFile, out.join('\n'), 'utf8');

                this.fileIn = this.tempFile;
            } else if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type === 'gcc') {
                this.fileIn = options.fileIn;
            }

I guess the condition should be updated to include uglifyJs as well:

       if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && options.type !== 'gcc' && options.type !== 'uglifyjs'  ) 

and:

            else if (typeof options.fileIn === 'object' && options.fileIn instanceof Array && (options.type === 'gcc' || options.type === 'uglifyjs' )) 

Update Readme

Update Readme and split examples in another file.

Broken on Windows because of YUICompressor-2.4.8 bug

Just to be aware: currently node-minify might be unable to process full paths on Windows correctly because of this bug:
yui/yuicompressor#78

I spent almost an hour debugging the issue until I came to that bug. I guess, it would be better to revert to 2.4.7 until they fix the issue.

Or you could try to create a workaround - writing to a temp file in relative path and then back to the final target.

still having the same issue.

may be you should be checking for entire directory instead of just __dirname + '/../node_modules something like below .

var getPath = function(bin) {
nodeModulesV2 = path.normalize(__dirname + '/../node_modules/'+bin);
isNPMv2 = dirExistsSync(nodeModulesV2);
dirToScan = isNPMv2 ? nodeModulesV2 : '';
var binPath = glob.sync(dirToScan + '**/.bin/' + bin +
((platform === 'win32') ? '.cmd' : ''), {realpath: true})[0];
console.log(binPath);
if (!binPath) {
throw new Error(bin + ' not found !');
}
return binPath;

ENOENT error when `_fs.unlinkSync(self.tempFile);` was performed

This happened occasionally while I was using uglifyjs. I added two console.log statements in node-minify.js one was after tempFile was set in minify function, the other was just before the deletion code. And I found in some cases the temp file name was the same for two node-minify instances. I think this is because you generate the file name based on current time but in some cases it runs fast so that two tem files would have the same name. So when you tried to delete the second minify will raise error as the temp file had been deleted by the one before. How about using uuid to generate temp files.

Callback Error object

Hi srod,

I'm trying to implement this pretty asynchronous minifier,
I've downloaded it, required it, but the minify function always give me back the error arg, and it doesn't work.

I'm working on a node-webkit app on a windows system (the app is supposed to be available on Linux / Mac / Windows).

And I call the minifier in this way :
var minifier = require('node-minify');
[...]
new minifier.minify({
type: 'uglifyjs',
fileIn: ["C:\Users...\main.js", ...],
fileOut: "C:\Users...\app.min.js",
buffer: 1000 * 1024,
callback: function (e) {
console.log('callback error', e);
}
});

The full error object is :
Error {
killed: false,
code: 1,
signal: null
}

I was asking myself if it was caused by the absolute filepaths, but I do not have the choice, because I am working on a new created folder (created with fs.mkdirSync...).
I've tried both linux-style and windows-like filepaths (C:... and C:/...).
I create the output file and it is working, but it do not put the minified content on it.

Do you have an idea ?

add a node-based css compressor

in my situation , java-based compressor is not sutable ( java process handleing is not stable so my compilation sometimes incomplete), so I wish you could also embed a Javascript-written css compressor in your lib. e.g. https://github.com/ded/sqwish .

BTW, your minifier is amazing 👍

UglifyJS copyright option no longer working

The copyright option no longer preserves the copyright at the top of files. I've done some digging and I believe this is why:

A few months ago, uglify-js on the npm registry was replaced with version 2. Version 2 takes the options after the file name. Version 1 used to take options before the file name.

Your package.json asks for any version * of uglify-js, which is why this now breaks.

Two options to fix it: either specify a version in the package.json instead of * or reorder the operations for uglifyjs. If you specified * as a personal preference, then the obvious choice is to reorder the operations.

CLI Mode

Is it possible to run it in command line mode? Tried with npm install node-minify -g for global module but it doesn’t work…

yui-js is not working

I'm haivng issues where yui-js is not working. It looks like running this via grunt the 'child_process' is not working.

UPATE : Setting auto path detection like other modules.

Is there any way we cannot have to set full path to node-minify.js for accessing require('c:/users/name/appdata/roaming/npm/npm_module/node-minify/libs/node-minify');
When i have server compressor js file one different location, i have to set full path to make it work, can i do it like using require('http"), require('express'), and so on require('node-minify')?

_fs.unlinkSync causing ENOENT on Windows

Found on windows - i suspect if multiple instances of minify is used concurrently - an error is thrown in some cases :

e.g.

events.js:72
throw er; // Unhandled 'error' event
^
Error: ENOENT, open 'E:\apps\Atajo-Lims\server\1418288361318-7115bbef-e515-4213-a513-36121e88f381'

Resolved by changing line 121 of node-minify.js to async unlink - e.g.

_fs.unlink(self.tempFile, function(err) {

                    if(err) { console.log("UNLINK ERROR : "+err); }
                      else { }

});

Optional return minified script as string rather than saving?

I'm keen to use this on launch of my server to hold a concatenated and minified version of my client app for serving.

For various reasons, I'd like to not save this first and just have it returned as a string as this will save me two file operations on launch.

Any feasibility in doing this?

Many thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.