Home Web Front-end JS Tutorial How to implement gulp packaging using nodejs

How to implement gulp packaging using nodejs

Jun 19, 2018 pm 02:41 PM
gulp nodejs code Package deployment

因为之前一直有人给我推荐gulp,说他这里好哪里好的。实际上对我来说够用就行。grunt熟悉以后实际上他的配置也不难,说到效率的话确实是个问题,尤其项目大了以后,目前位置遇到的项目都还可以忍受。不过不管怎么说,需要亲自用过gulp之后才能品评他和grunt之间的优劣。

最近换了家新公司,由于是创业公司,项目基本从零开始搭建。工作几年,也没想过写点什么技术性的东西,今天突然心血来潮,哦当然,我这个人总是特别容易心血来潮,不定想干点啥,不说废话了,毕竟上班呢,开小差也不太好。忙了一个月,项目初见雏形,也基本可以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;
Copy after login

这只是个最简单的小例子,要是有其它的往里加就好了,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;
Copy after login

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

下面是gulpfile.js文件:

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

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

.babelrc内容:

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

有的小伙伴可能会遇到版本号不断叠加的问题,还记得{ 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);
Copy after login

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
);
Copy after login

这段改为

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})*" );
Copy after login

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

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

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

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用React如何防止出现重复渲染

在vue中如何实现directive功能

在nodejs中基于mssql模块如何实现封装

在Javascript中如何实现bind

在js中如何实现二级联动

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

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles