这次给大家带来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中文网其它相关文章!
推荐阅读:
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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.