search
HomeWeb Front-endJS TutorialHow to implement gulp packaging function in nodejs

这次给大家带来nodejs怎么实现gulp打包功能,nodejs实现gulp打包功能的注意事项有哪些,下面就是实战案例,一起来看一下。

最近换了家新公司,由于是创业公司,项目基本从零开始搭建。工作几年,也没想过写点什么技术性的东西,今天突然心血来潮,哦当然,我这个人总是特别容易心血来潮,不定想干点啥,不说废话了,毕竟上班呢,开小差也不太好。忙了一个月,项目初见雏形,也基本可以1.0上线了,趁着等文案的时间,简单写点gulp打包的东西,等明儿有空再来一篇详细的,再有空再来个webpack的,哎呀,这个有空也不知道是啥时候,莫怪,好像又废话了几句。stop,stop。

从头儿来吧,首先创建一个package.json文件,就npm init一直确认确认确认就好了,构建过程中用到什么就npm什么就好了。做过vue脚手架的小伙伴儿应该知道,脚手架会自动生成一个特别全面的package.json文件,当然我们目前也用不到那么多。不多说了。

为了万一以后添加强大的功能,我们就多做几个文件,就不是仅仅一个gulpfile.js了,当然一个也没问题。

来创建一个gulpfile.config.js来专门放置文件路径引用输出等。就是所谓的src,dist。再来一个gulpfile.xxx.js,名字随便起吧,引用的时候引用对就好了。再来一个gulpfile.js吧,最后要运行啊。

做个最简单例子,以js压缩为例,稍后加上版本哈管理功能,用法都差不多,用什么加什么。

var src_file = './xxxx/'; // 你的源文件目录
var dist_file= './dist/xxxx/'; // 文件处理后你想存放的目录
var config= {
src: src_file,
dist: dist_file,
js: {
  src: src_file + 'src/js/**/*.js',      // 你的js目录
  dist: dist_file + 'src/js',         // js文件打包后存放的目录
  },
};
module.exports = config;

这只是个最简单的小例子,要是有其它的往里加就好了,html,css,img,还有一些静态文件等。

关键的来了,我们把处理方法写在gulpfile.xxx.js里面。

gulpfile.xxx.js:

var gulp = require('gulp');
var rename = require('gulp-rename'); //重命名
var babel = require("gulp-babel");
var uglify = require('gulp-uglify'); //js压缩
var config = require('./gulpfile.config.js');
var runSequence = require('run-sequence');
var rev = require('gulp-rev');//版本号管理的一些东西,先写进来吧,懒的在敲了
var revCollector = require('gulp-rev-collector');
var cssUrl = './dist/xxx/src/css/*.css',
   jsUrl = './dist/xxx/src/js/*.js';
function haha() {
  gulp.task('js', function () {
    return gulp.src(Config.js.src)
          .pipe(babel())
          .pipe(uglify())
          .pipe(gulp.dest(config.js.dist));
    });
  gulp.task('revJs', function(){
    return gulp.src(jsUrl)
          .pipe(rev())
          .pipe(rev.manifest())
          .pipe(gulp.dest('dist/xxx/src/js'));
  });
  gulp.task('revHtml', function () {
        return gulp.src(['dist/xxx/src/js/**/*.json', 'chaohuo/*.html']) /*后面本地html文件的路径,可自行配置*/
          .pipe(revCollector(
            { replaceReved:true }
            ))
          .pipe(gulp.dest('dist/chaohuo')); /*Html更换css、js文件版本,和本地html文件的路径一致*/
  });
  gulp.task('dev', function (done) {
      condition = false;
      runSequence(
          ['revJs'],
          ['revHtml'],
    done);});
    gulp.task('default', ['js','dev']);
}
module.exports = haha;

天啊,我本来想一步步来写清楚点的,没想到一下子把版本号相关的也都写进去了,那就算了吧,一起来吧。

下面是gulpfile.js文件:

var haha= require('./gulpfile.prod.js');
haha();

基本工作已经完成一大半了,还有一个忘记说了。如果你用到了es6语法,千万别忘记配置一个.babelrc文件.

.babelrc内容:

  "presets": [
    "es2015",
  ],
  "plugins": [
    "transform-remove-strict-mode"//这个插件就是添加版本号的关键。
  ]
}

有的小伙伴可能会遇到版本号不断叠加的问题,还记得{ replaceReved:true }这个吗,前面有看一下,记得添加这个。还有最后一步node_modules我们要更改一些代码,来吧,我下的最新的包(如果你用的老的,也是差不多的改法),替换下。

gulp-path里的index.js两个return的东西都改掉:

return modifyFilename(pth, (filename, ext) => `${filename}-${hash}${ext}`);改为return modifyFilename(pth, (filename, ext) => `${filename}${ext}`);
return modifyFilename(pth, (filename, ext) => filename.replace(new RegExp(`-${hash}$`), '') + ext);改为return modifyFilename(pth, (filename, ext) => filename + ext);

gulp-rev-collector里的index.js:

大概128行左右 

patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) )
+ path.basename(key, path.extname(key))
.split('.')
.map(function(part){
return escPathPattern(part) + '(' + opts.revSuffix + ')?';
})
.join('\\.')
+ patternExt
);

这段改为

patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) + path.basename(key, path.extname(key)) ) + opts.revSuffix + escPathPattern( path.extname(key) ) + "(\\?v=(\\d|[a-z]){8,10})*" );

这里相关的也是网上查了很多相关的资料,不过好像都是一些老版本,并且gulp-rev里的文件不用修改,这里也经过多次测试,以上基本可用。

好了,离成功不远了,cmd运行下gulp命令,ok,基本完成,可以去查看下啦!

注意:所有require的东西记得npm安装哦,卡的话就cnpm,不多说。

还有由于很多东西都是手打的,可能会有部分拼写呀,文件路径的错误,记得检查更改哦。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JS的JSON数据分组怎样优化

vue+init失败怎么处理

The above is the detailed content of How to implement gulp packaging function in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft