Code Monkey home page Code Monkey logo

gulp-md5-plus's Introduction

gulp-md5-plus

md5 plugin for gulp ,md5 the static files(eg javascript style image files) ;then replace the filenames in css or the html if needed by passing the file or dir in the second parameter

Usage

First, install gulp-md5-plus as a development dependency:

npm install --save-dev gulp-md5-plus

Then, add it to your gulpfile.js:

var md5 = require("gulp-md5-plus");

gulp.src("./src/*.css")
	.pipe(md5(10,'./output/index.html'))
	.pipe(gulp.dest("./dist"));

md5 all css files in the src folder and change these css names in the quoted html--index.html

gulp.task('img' ,function() {
    var imgSrc = './static/img/**',
        quoteSrc = './output/static/css/**/*.css', // [./output/static/css/**/*.css',./output/static/js/**/*.js']
        imgDst = './output/static/img';

    return gulp.src(imgSrc)
        .pipe(imagemin())
        .pipe(md5(10 ,quoteSrc))
        .pipe(gulp.dest(imgDst));
});

first, optimize all images in the img folder including all sub folders; then md5 all these images and change these images' names in the quoted css files ;

####note the directory of the md5ed files in the imgDst folder is the same as that of original files in the imgSrc folder; and css files can refer the image file with the same name in different folder rightly;

API

md5(size,file,option)

size

Type: String

Default: null

you can pass the size to limit the size of the hash that is appended.

file

Type: String

Default: null

the file need to replace the file name of the md5ed files. dir is also supported

option

Type: Object

Default: null

option.dirLevel

Type: Number

Default: null

used to match the file with it's directory path. for example: there is a file Dev/work/gulp-md5-plus/demo/source/img/sub_img/same.svg;when setting dirLevel to 1, the plugin will use sub_img/same.svg to find this file in the quoted files;this option's main purpose is to replace the files with the same name in different paths. you can see demo for detail.

Example:

	gulp.task('img' , ['css'],function() {
	    gulp.src('./source/img/**/*')
	        .pipe(md5(10 ,'./output/css/*.css',{
	        	dirLevel : 1,
	        	mappingFile: 'manifest.json',
        		connector: '.'
	        }))
	        .pipe(gulp.dest('./output/img/'));
	});

The sample above will append the md5 hash(length : 10) to each of the file in the static/js folder then repalce the link file name in the output/html/ using md5ed file name; at last store all of that into the output folder.

option.connector

Type: String

Default: _

used to set the output file‘s connector; if use . the outfile will look like imgfile.5546983ac2.png ,while default is imgfile_5546983ac2.png

option.mappingFile

Type: String

Default: null

set the file to write the mapping result ,for example manifest.json

after set this option ;you should remove this file before gulp; you can follow the demo;

Demo

I have add a demo to demonstate how to use this plugin; If you have any other questions ,pls add issues.

License

http://en.wikipedia.org/wiki/MIT_License[MIT License]

gulp-md5-plus's People

Contributors

david-eddy avatar gaborage avatar miaotmac avatar wpfpizicai 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

Watchers

 avatar

gulp-md5-plus's Issues

how about try to match the quoteSrc as an array

gulp.task('md5Img' ,function() {
    var imgSrc = [image + '/**/*','!'+image+"/fonts/*"],
        //next line will throw an error because gulp-md5-plus does not yet support this way of writing
        quoteSrc = ['./shidou/*.html',com_css + '/**/*.css',com_js + '/**/*.js'];

    return gulp.src(imgSrc)
        .pipe(md5(10 ,quoteSrc))
        .pipe(gulp.dest(image));
});

IMO,this`ll be more convinient as quoteSrc could math the ARRAY type also :)

The "dirLevel" does't work

The "dirLevel" of option does't work in your demo, I have tried some times, either. You said in document that "dirLevel" is used to replace the files with the same name in different paths, but when used, nothing will happen.

Option 'dirLevel' has a bug with Windows

I hava some files like this:

build/css/main.min.css
build/js/app.min.js

then I put them in html files:

<link href="//cdn.bootcss.com/css/main.min.css" rel="stylesheet">
<link href="/css/main.min.css" rel="stylesheet">
<script src="/js/app.min.js" type="text/javascript"></script>

I want replace app.min.js and main.min.css, so I set option.dirLevel = 1.
It works fine in Mac and other Linux platform, but it's broken in Windows.

I take some logs, then I found the secrect.
Mac & Linux:
use js/app.min.js to replace
Windows:
use js\app.min.js to replace

So, how to resolve? add a option sep to replace?

Issue with similar filename strings

I have this CSS code:

@font-face {
    font-family: "icons";
    src: url('/fonts/icons.eot');
    src: url('/fonts/icons.eot?#iefix') format('eot'),
        url('/fonts/icons.woff2') format('woff2'),
        url('/fonts/icons.woff') format('woff'),
        url('/fonts/icons.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

See how icons.woff and icons.woff2 are the same except for the 2 at the end? At the moment both are being replaced with the same thing:

url(/fonts/icons_c5c3b.woff2) format("woff2"),
url(/fonts/icons_c5c3b.woff) format("woff"),

The expected result is that both are treated as separate things:

url(/fonts/icons_12db4.woff2) format("woff2"),
url(/fonts/icons_c5c3b.woff) format("woff"),

Looks like the string replacing regex might need to be tweaked. I'll have a go, but I'm no js wizz. Or maybe is there some hack I could do?

引用三方js,js名被改变

一个html里面的三方script链接,
压缩之前:

<script type="text/javascript"> document.write('<script src="\/\/assets-cdn.kf5.com\/supportbox\/main.js?' + (new Date).getDay() + '" id="kf5-provide-supportBox" kf5-domain="rouchiyy.kf5.com" charset="utf-8"><\/script>'); </script>

压缩之后:

<script type=text/javascript> document.write('<script src="\/\/assets-cdn.kf5.com\/supportbox\/main_d41d8cd98f.js?' + (new Date).getDay() + '" id="kf5-provide-supportBox" kf5-domain="rouchiyy.kf5.com" charset="utf-8"><\/script>'); </script>

main.js名字被改变了,实际上不应该被改变,请问如何解决

sourcermaps

Hi!

Thank you for the module. It's very useful.

I'm sorry, but I'm having a hard time with sourcemaps. They're being renamed, but not the references to them.

Can you, please, update the sample usage with how to proceed in this case?

Thank you!

You may need to republish the version on `npm`

At present you released the version at npm is a wrong version, I hope you can update once again, thank you.

You need the jsonfile module, but you did not write it into the package.json

img MD5 problem

.a {
    background: url(img/abc.png) -1px -1px;
}
.b {
    background: url(img/abc.png) 51px -1px;
}

afer md5:

.a {
    background: url(img/abc_b658203603.png) -1px -1px;
}
.b {
    background: url(img/abc.png) 51px -1px;
}

index.js at line 42 and 51, I deal with like this:

var result = fs.readFileSync(i_ilist,'utf8').replace(new RegExp(filename,"g"), md5_filename);

I hope I can express clearly.

Cannot find module 'jsonfile'

Error: Cannot find module 'jsonfile'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (D:\github\gulp-webpack-demo\node_modules\gulp-md5-plus\index.js:7:14)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

There was a problem with the same name of the file to replace the file in a different path

hi,

I really like this plugin, great resolve caching issues,but there was a problem with the same name of the file to replace the file in a different path, E.g:

<link rel="stylesheet" href="__DOMAIN__static/boss/css/colors/dwd.css">
<link rel="stylesheet" href="__DOMAIN__static/css/dwd.css">

When replace the file name, if the ratio of the path, I can solve this problem, Add path sub_namepath

if(Object.prototype.toString.call(ifile) == "[object Array]"){
    ifile.forEach(function(i_ifile){
        i_ifile && glob(i_ifile,function(err, i_files){
            if(err) return console.log(err);
            i_files.forEach(function(i_ilist){
                var result = fs.readFileSync(i_ilist,'utf8').replace(new RegExp(sub_namepath + filename + '[^a-zA-Z_0-9].*?' ,"g"), function(sfile_name){
                return sfile_name.replace(sub_namepath + filename,sub_namepath + md5_filename)
            });
                fs.writeFileSync(i_ilist, result, 'utf8');
            })
        })
    })
}else{
    ifile && glob(ifile,function(err, files){
        if(err) return console.log(err);
        files.forEach(function(ilist){
            var result = fs.readFileSync(ilist,'utf8').replace(new RegExp(sub_namepath + filename + '[^a-zA-Z_0-9].*?' ,"g"), function(sfile_name){
                return sfile_name.replace(sub_namepath + filename,sub_namepath + md5_filename)
            });
            fs.writeFileSync(ilist, result, 'utf8');
        })
    })
}

Can you update about what plug-ins, in order to support this demand, thankyou

filename with same of end, will be replaced incorrect

If I use two JavaScript file in html, like this:

<script type="text/javascript" src="/static/dist/dev/js/item_detail.js"></script>
<script type="text/javascript" src="/static/dist/dev/js/my_item_detail.js"></script>

Then, both item_detail.js and my_item_detail.js will be add the md5 of item_detail.js.
For example:

<script type="text/javascript" src="/static/dist/dev/js/item_detail_7b61c.js"></script>
<script type="text/javascript" src="/static/dist/dev/js/my_item_detail_7b61c.js"></script>

It can be resolved by add '/' before filename at line42 and line53 of [email protected] in Windows system.

 var result = fs.readFileSync(i_ilist,'utf8').replace(new RegExp('/' + filename + '[^a-zA-Z_0-9].*?' ,"g"), 

How about 'manifest.json'?

Hello!
Like gulp-rev, I wanna get a mainfest.json file after md5

{
    "demo/index.js":"demo/index_f6f643a99a.js"
}

then I can know the mapping between origin files and dist files

how could I ?

DIY like this?

//...
.pipe(
    (function(){
          return through2.obj(function(file, enc, cb){
              //record file.path to create manifest.json
              //...
              cb(null,file);
          });
     })()
);

HTML code reference img

If the HTML code has a reference to the IMG image, how to make img plus MD5 stamp

<div class="qrcode"><img src="images/qrcode2.png" alt=""></div>

v0.2.5 still have a little problem

#8 problem is unfixed,still have a little problem. different path and different file,but replaced as a last file

<link rel="icon" type="image/png" href="//static.doweidu.com/static/iqg/favicon_9d14bbe40c.png">
<link rel="icon" type="image/png" href="//static.doweidu.com/static/hsq/favicon_9d14bbe40c.png">

should be

<link rel="icon" type="image/png" href="//static.doweidu.com/static/iqg/favicon_01113cdd06.png">
<link rel="icon" type="image/png" href="//static.doweidu.com/static/hsq/favicon_9d14bbe40c.png">

Won't append to files without relative path

This works:

<!-- build/index.html -->
<link rel="stylesheet" href="./styles.css"> 
// gulpfile.js
gulp.task('compile', () => {
  gulp.src(['./index.css'])
    .pipe(md5(10, './build/index.html'))
    .pipe(gulp.dest('./build'));
});

This does not:

<!-- build/index.html -->
<link rel="stylesheet" href="styles.css"> 
// gulpfile.js
gulp.task('compile', () => {
  gulp.src(['index.css'])
    .pipe(md5(10, './build/index.html'))
    .pipe(gulp.dest('./build'));
});

The CSS file still correctly gets processed by Gulp, but gulp-md5-plus won't recognize it in the HTML file without the ./ before the file name, even though everything is valid. This may not be a critical bug, but it's far more common for paths in HTML to be written assuming the path is relative rather than explicitly stating it.

Getting generated filenames

Hi there,
First off, let me say thank you so much for this plug-in !
It is exactly what I was looking for, and so easy and elegant to implement.
Before this plugin, I fiddled with "specified" cache busting plugins like gulp-rev or gulp-bust, and a few others. But none of them really worked as they should, and definitely not as uncomplicated as yours !

Well, enough of the praise and to my issue:
I need to modify the linked references in a .css file that itself is generated by gulp-md5-plus.
As the file is generated in the process, I can not exactly specify it in the parameter.

Is it possible to get the generated filename of a md5-plus action in order to use it later on in the task?

For example:

var new_main_css_filename = "";

gulp.task("style", function() {
    return gulp.src( Source.style )
        .pipe( md5(10, "./" + output_folder + '/index.html') )
            .on("done", function(event) {
                new_main_css_filename = event.filename[1];
            }
        )
        .pipe( gulp.dest(output_folder + "/css/") )
});

gulp.task("image_assets", function() {
    return gulp.src( Source.other_assets , { cwd: source_folder } )

        .pipe( md5(10, "./" + output_folder + "css/" + new_main_css_filename ) )

        .pipe( gulp.dest(output_folder) )
});

Issue with file.path

Hi,

I got following issue:

[13:34:49] Finished 'watch:sass' after 46 ms
events.js:160
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open 'D:...\dist\sources.js?7ec9346c08'
at Error (native)

And it's solved only after remove the line
43: file.path = path.join(dir, md5_filename);

Another issue - sometimes I got following situation:
<link rel="stylesheet" href="/app/sources.css?525b3c5c4c?525b3c5c4c?525b3c5c4c?525b3c5c4c">

I solved it by changing line:
38: var result = fs.readFileSync(ilist,'utf8').replace(new RegExp(escapeRegExp(sub_namepath + filename)+'(.*?)((?=\")|(?=\'))', "g"), sub_namepath + md5_filename);
i.e. added to regular expression additional keys
'(.*?)((?=\")|(?=\'))'

you can check it on
/sources\.css+(.*?)((?=\")|(?=\'))/g
with content like

<link rel="stylesheet" href="/app/plugins/angularjs-slider-master/dist/rzslider.min.css">
<link rel="stylesheet" href="/app/plugins/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/app/plugins/FlipClock-master/compiled/flipclock.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="/app/sources.css?525b3c5c4c?525b3c5c4c?525b3c5c4c?525b3c5c4c' sdcd="d"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<title>Title</title>
<base href="/app">

This can help improve the module.
Thanks,
Max

jsonfile wrong dependency reference

Hi.

Shouldn't the jsonfile be listed as a dependency, instead of a "devDependency"? As it is required to the plugin be used, instead of only for it to be build, I think it should.

Thank you!

Option to choose separating character

Adding an option to choose the separating character would be nice. My personal preference is to use - rather than the current _ default. It would also allow for someone to not use a separator by specifying an empty value.

´+´ on filenames

Hi!

Files with + on their names are renamed, but their references aren't replaced.

store+json2.min.js is renamed to store+json2.min_d162e09f27.js, but the HTML remains:

<script src="/dist/vendor/store/store+json2.min.js"></script>

Thank you!

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.