gulp-imagemin_如何使用Gulp和gulp-imagemin缩小图像并提高网站性能

gulp-imagemin

Images are everywhere across the internet. You would be hard pressed to find a single page or application that doesn’t contain at least one image in some form or another. Images are great way to help tell stories and emphasize critical parts of our lives.

图像遍布互联网。 您将很难找到一个页面或应用程序,其中至少不包含某种形式或另一种形式的图像。 图像是帮助讲述故事并强调生活关键部分的好方法。

But if you’re like me you know that having a large image can seriously impact the performance of your site/app. So today, I’m going to teach you how to use Gulp and an npm package called gulp-imagemin to reduce the size of your images on the fly.

但是,如果您像我一样,就会知道拥有较大的图像会严重影响您的网站/应用的性能。 因此,今天,我将教您如何使用Gulp和一个名为gulp-imageminnpm软件包来gulp-imagemin减小图像的大小。

If you don’t know what all of these words mean, fear not! I have some relevant and important links/descriptions below to help bring you up to speed.

如果您不知道所有这些单词的含义,请不要担心! 我在下面提供了一些重要的相关链接/说明,以帮助您快速入门。

  • Minification, or minifying as I like to call it, is the act or process of removing unnecessary parts of source code to reduce size.

    缩小或我所称的缩小是删除源代码不必要的部分以减小大小的行为或过程。

  • Gulp is a JavaScript build tool that allows you to automate parts of your workflow to streamline your process. It takes care of some not so interesting, but important, aspects of your workflow (like reducing image size) so that you can focus on the building. You can find Gulp here.

    Gulp是一个JavaScript构建工具,可让您自动化工作流程的各个部分以简化流程。 它会处理工作流程中一些不太有趣但很重要的方面(例如减小图像大小),以便您可以专注于建筑物。 您可以在这里找到Gulp

  • To make use of npm we'll need to install Node.js which is, in a nutshell, the framework that allows developers to use JavaScript code in a server (back end) environment. You can find Node here.

    要使用npm我们需要安装Node.js ,简而言之,该框架使开发人员可以在服务器(后端)环境中使用JavaScript代码。 您可以在此处找到Node

  • npm (Node Package Manager) is and does what its name implies. It is a package manager for JavaScript and "the world's largest software registry". Just think of npm as a giant storage area for awesome packages/utilities to help developers. You can find npm here.

    npm (节点程序包管理器)就是它的名字,并且按照其名称的含义行事。 它是JavaScript和“世界上最大的软件注册表”的软件包管理器。 只需将npm视为巨大的存储区,即可使用强大的软件包/实用程序来帮助开发人员。 您可以在此处找到npm

  • gulp-imagemin is one of those awesome packages I mentioned earlier. Using this package we'll be able to automatically reduce the size of our images every time a save occurs. You can find gulp-imagemin here.

    gulp-imagemin是我之前提到gulp-imagemin软件包之一。 使用此程序包,我们将能够在每次保存时自动减小图像的大小。 您可以在这里找到gulp-imagemin

Alright, now that explanations are out of the way let’s get to the fun parts :D

好了,现在已经不再需要解释了,让我们进入有趣的部分:D

项目文件结构 (Project File Structure)

Start by opening up your text editor of choice and creating a directory for your project or if you have an existing directory navigate to that directory in your terminal and skip down to the Installing Node & npm Section.

首先打开您选择的文本编辑器并为项目创建目录,或者如果您已有目录,请导航至终端中的该目录,然后跳至“ 安装节点和npm”部分

If you’re using VS Code you can find the built in terminal by hitting ctrl + ` (tilde).

如果您使用的是VS Code ,则可以通过按ctrl + ` (tilde)找到内置终端

Here’s how my project structure looks in my terminal:

这是我的终端中项目结构的外观:

And here’s how my project file structure looks in the explorer inside VS Code:

这是我的项目文件结构在VS Code中在资源管理器中的外观:

As you can see I have a separate directory for my base files and the minified files. Once you have your project directory established it’s time to start installing everything we’ll need.

如您所见,我的基本文件和缩小的文件都有一个单独的目录。 建立项目目录后,就该开始安装我们需要的所有内容了。

安装Node&npm (Installing Node & npm)

Alright, now that our directory is up and running let’s start installing our dependencies. If you already have Node & npm installed, feel free to skip down to the Installing Gulp & gulp-imagemin Section.

好了,既然我们的目录已经启动并且正在运行,让我们开始安装依赖项。 如果您已经安装了Node & npm ,请随时跳至Installation Gulp和gulp-imagemin部分

  1. First, enter node --v within your terminal to check and see if you have the Node installed. If you do, you'll get something back like v8.9.3

    首先,在终端中输入node --v ,以检查是否安装了节点。 如果这样做,您将获得类似v8.9.3

  2. If you get nothing back or an error, simply download and install Node from here. It could take a few minutes so +be patient.

    如果您没有得到任何回报或出现错误,只需从此处下载并安装Node 。 可能要花费几分钟,因此请耐心等待。

  3. Once Node.js is installed, you'll have npm installed as well because it comes bundled with Node. You can check the version of npm by typing npm -v in your terminal. You should get something like 6.4.1back.

    安装Node.js ,您npm安装npm ,因为它与Node捆绑在一起。 您可以通过在终端中键入npm -v来检查npm的版本。 您应该返回6.4.1

  4. Next we need to create a package.json file for our project. We do this by using the command npm init (find out more about package.json here). You'll be asked a series of questions but if you don't want to answer them you don't have to, just hit enter until you see Is this OK? (yes), then hit Enter one last time and you'll be finished with this section.

    接下来,我们需要为我们的项目创建一个package.json文件。 我们通过使用命令npm init ( 在此处找到有关package.json更多信息)来进行此操作。 您将被问到一系列问题,但是如果您不想回答这些问题,则不必输入,只需按Enter键,直到看到Is this OK? (yes) Is this OK? (yes) ,然后最后一次Enter ,您将完成本节。

You’ll notice that this file was created in a different directory than the one I started with. This is so I can provide an example, as I have previously installed all of this in my current project directory.

您会注意到,该文件是在与我开始时所在的目录不同的目录中创建的。 这样一来,我可以提供一个示例,因为我之前已将所有这些都安装在当前项目目录中。

安装Gulp和gulp-imagemin (Installing Gulp & gulp-imagemin)

Once Node & npm have been installed, we can now install Gulp & gulp-imagemin by following these steps:

安装Node & npm ,我们现在可以按照以下步骤安装Gulp & gulp-imagemin

  1. First, type npm install --save-dev gulp in your terminal. If you want to know what the --save-dev flag does, check out this Stack Overflow post.

    首先,在终端中键入npm install --save-dev gulp 。 如果您想知道--save-dev标志的作用,请查看此Stack Overflow post

  2. Again, be patient as installing Gulp might take a minute but you’ll eventually end up with something like this: gulp@4.0.0 added 318 packages from 218 contributors and audited 6376 packages in 49.362s found 0 vulnerabilities

    同样,请耐心等待,因为安装Gulp可能需要一分钟,但最终您会得到这样的结果: gulp@4.0.0 added 318 packages from 218 contributors and audited 6376 packages in 49.362s found 0 vulnerabilities

  3. You can check your Gulp version by typing gulp -v in your terminal and you'll get something similar to this: [13:06:56] CLI version 2.0.1 [13:06:56] Local version 4.0.0

    您可以通过在终端中键入gulp -v来检查Gulp版本,您将获得类似以下内容: [13:06:56] CLI version 2.0.1 [13:06:56] Local version 4.0.0

  4. Now let’s install gulp-imagemin by typing npm install --save-dev gulp-imagemin and again you'll get something like this back: gulp-imagemin@5.0.3 added 232 packages from 97 contributors and audited 10669 packages in 39.103s found 0 vulnerabilities

    现在,让我们通过键入npm install --save-dev gulp-imagemin gulp-imageminnpm install --save-dev gulp-imagemin ,您将再次得到类似的信息: gulp-imagemin@5.0.3 added 232 packages from 97 contributors and audited 10669 packages in 39.103s found 0 vulnerabilities

  5. And the final step for this section is to create our gulpfile.js It is very important that your file has this exact name and is in the outer most level of your project folder structure!

    这部分的最后一步是创建我们的gulpfile.js 。文件具有这个确切的名称并且位于项目文件夹结构的最外层非常重要!

编写代码-最后就是乐趣! (Writing the Code — Finally the Fun!)

Ok, now that we’ve taken care of installing everything in the correct place, let’s open up our gulpfile.js and write the actual code that will do all of the hard work.

好的,既然我们已经将所有内容都安装在正确的位置,那么让我们打开gulpfile.js并编写完成所有艰苦工作的实际代码。

  1. Start by requiring gulp --> const gulp = require('gulp');We're basically taking advantage of Node's module system to use code that is located in different files

    首先需要gulp -&g t; const gulp = require('gulp t; const gulp = require('gulp ');我们基本上是利用Node的模块系统来使用位于不同文件中的代码

  2. Now require gulp-imagemin --> const imagemin = require('gulp-imagemin'); Again we're taking advantage of the module system to use this code in our project

    现在需要gulp-imagemin &g t; const imagemin = require('gulp-imagemin t; const imagemin = require('gulp-imagemin '); 同样,我们利用模块系统在我们的项目中使用此代码

  3. Now, we need to write the function that will do all of the image squashing:

    现在,我们需要编写将完成所有图像压缩的函数:

    Now, we need to write the function that will do all of the image squashing: function imgSquash() {

    现在,我们需要编写将完成所有图像function imgSquash() {function imgSquash() {

    Now, we need to write the function that will do all of the image squashing: function imgSquash() { return gulp .src("./img/*")

    现在,我们需要编写将完成所有图像function imgSquash() {function imgSquash() { return gulp . src("./img/*") function imgSquash() { return gulp . src("./img/*") return gulp . src("./img/*")

    Now, we need to write the function that will do all of the image squashing: function imgSquash() { return gulp .src("./img/*") .pipe(imagemin())

    现在,我们需要编写将完成所有图像function imgSquash() {function imgSquash() { return gulp . src("./img/*") function imgSquash() { return gulp . src("./img/*") return gulp . src("./img/*") . pipe(imagemin()) . pipe(imagemin())

    Now, we need to write the function that will do all of the image squashing: function imgSquash() { return gulp .src("./img/*") .pipe(imagemin()) .pipe(gulp.dest("./minified/images"));

    现在,我们需要编写将完成所有图像function imgSquash() {function imgSquash() { return gulp . src("./img/*") function imgSquash() { return gulp . src("./img/*") return gulp . src("./img/*") . pipe(imagemin()) . pipe(imagemin()) . pipe(gulp . dest("./minified/images")); . pipe(gulp . dest("./minified/images"));

    Now, we need to write the function that will do all of the image squashing: function imgSquash() { return gulp .src("./img/*") .pipe(imagemin()) .pipe(gulp.dest("./minified/images"));}

    现在,我们需要编写将完成所有图像function imgSquash() {function imgSquash() { return gulp . src("./img/*") function imgSquash() { return gulp . src("./img/*") return gulp . src("./img/*") . pipe(imagemin()) . pipe(imagemin()) . pipe(gulp . dest("./minified/images")); . pipe(gulp . dest("./minified/images")); }

  4. If you set your directory up following mine, the code above will work. If your directory looks different you will need to change the .src & .dest lines to match where your files are located and where you want them piped to after they've been minified.

    如果您按照我的方式设置目录,则上面的代码将起作用。 如果目录看起来不同,则需要更改.src & .dest行以匹配文件的位置以及将它们缩小后希望通过管道传输到的位置。

  5. Gulp operates based off of tasks and we can give it plenty of those to keep it busy. Once we've defined the actual function to do the heavy lifting, we need to tell Gulp what to do with that function: gulp.task("imgSquash", imgSquash);

    Gulp根据任务进行操作,我们可以提供很多任务来保持任务繁忙。 一旦定义了要执行繁重工作的实际功能,就需要告诉Gulp该功能如何处理: gulp.task("imgSquash", imgSquash);

  6. Now, we want Gulp to watch our given directory for changes (new images) and when it detects those, we want it to automatically run our imgSquash function, minify our images, and pipe them to the destination we set. We achieve that by defining another task to watch the directory:

    现在,我们希望Gulp监视给定目录中的更改(新图像),当它检测到更改时,我们希望它自动运行imgSquash函数,缩小图像并将它们通过管道传递到我们设置的目的地。 我们通过定义另一个监视目录的任务来实现:

    Now, we want Gulp to watch our given directory for changes (new images) and when it detects those, we want it to automatically run our imgSquash function, minify our images, and pipe them to the destination we set. We achieve that by defining another task to watch the directory: gulp.task("watch", () => {

    现在,我们希望Gulp监视给定目录中的更改(新图像),当它检测到更改时,我们希望它自动运行imgSquash函数,缩小图像并将它们通过管道传递到我们设置的目的地。 我们通过定义另一个监视目录的任务gulp . task("watch", () =& gt; {来实现这一点gulp . task("watch", () =& gt; { gulp . task("watch", () =& gt; {

    Now, we want Gulp to watch our given directory for changes (new images) and when it detects those, we want it to automatically run our imgSquash function, minify our images, and pipe them to the destination we set. We achieve that by defining another task to watch the directory: gulp.task("watch", () => { gulp.watch("./img/*", imgSquash);

    现在,我们希望Gulp监视给定目录中的更改(新图像),当它检测到更改时,我们希望它自动运行imgSquash函数,缩小图像并将它们通过管道传递到我们设置的目的地。 我们通过定义另一个监视目录的任务gulp . task("watch", () =& gt; {来实现这一点gulp . task("watch", () =& gt; { gulp . task("watch", () =& gt; { g u lp.watch("./img/*", imgSquash);

    });

    });

  7. The last step to writing the code is defining the last task to call our imgSquash and watch tasks in succession: gulp.task("default",gulp.series("imgSquash","watch")); Here the word "default" refers to the word gulp in the terminal and the gulp.series will ensure that the imgSquash function runs and immediately after Gulp will watch the directory for changes.

    编写代码的最后一步是定义最后一个任务,以调用imgSquash并连续watch任务: imgSquash gulp . task("default",gulp . series("imgSquash","watch")); gulp . task("default",gulp . series("imgSquash","watch")); 这里所说的“默认”是指字gulp在终端和gulp.series将确保imgSquash功能运行和咕嘟咕嘟后,立即将手表目录更改。

Here is what our finished file should look like:

这是我们完成的文件的外观:

Save this file, open your terminal, and type gulp and hit enter. You should see something like this:

保存此文件,打开终端,然后输入gulp并按Enter。 您应该会看到以下内容:

As you can see, each time a new file was added to the base directory, our tasks kicked in because Gulp was watching and immediately ran our imgSquash function to minify our images. When you're finished using Gulp you can hit ctrl + c in your terminal to terminate the watch process.

如您所见,每次将新文件添加到基本目录时,由于Gulp正在监视并立即运行imgSquash函数以缩小图像,因此我们的任务开始了。 使用完Gulp后,您可以在终端中按ctrl + c终止监视过程。

Now you can start using your minified images on your website/app and enjoy that new found boost in performance!

现在,您可以开始在网站/应用上使用缩小的图像,并享受性能的全新提升!

结语 (Wrap Up)

Gulp is a very powerful JavaScript build tool that can help automate some of the more tedious, but important, aspects of building your project. With less than an hour’s worth of work you were able to get your images minified, thus reducing load time and increasing performance for your website/app. That’s awesome and you should be proud of yourself!

Gulp是一个非常强大JavaScript构建工具,可以帮助自动化构建项目中一些较繁琐但重要的方面。 通过不到一个小时的工作,您就可以缩小图像,从而减少加载时间并提高网站/应用程序的性能。 太棒了,您应该为自己感到骄傲!

This is just one of the many ways that build tools like Gulp can help you. There are many more ways it can help (minifying/concatenating CSS/JS files) and I hope you explore some of those awesome options.

这只是构建Gulp等工具可以为您提供帮助的众多方式之一。 它可以提供更多帮助(缩小/连接CSS / JS文件),我希望您能探索其中一些很棒的选项。

If you enjoyed this article please consider donating some claps as it helps others find my work. Also, drop a comment and let me know what you’re working on and how Gulp helps you focus on the building.

如果您喜欢本文,请考虑捐赠一些鼓掌,因为它可以帮助其他人找到我的作品。 另外,发表评论,让我知道您正在从事的工作以及Gulp如何帮助您专注于建筑物。

And finally, this article was originally posted on my personal blog. While you’re there don’t forget to sign up for the Newsletter which can be found at the top right corner of my blog page. I send it out monthly (I promise not to spam your inbox) and it’s filled with awesome articles from across the web that I think you’ll find helpful.

最后,本文最初发布在我的个人博客上 。 当您在那里时,请不要忘记注册新闻通讯 ,该新闻通讯可以在我的博客页面的右上角找到。 我每月发送一次(我保证不会向您的收件箱发送垃圾邮件),并且其中充满了来自网络上的很棒的文章,我认为您会发现有帮助。

As always, have an awesome day full of love, happiness, and coding!

一如既往,祝您拥有充满爱,幸福和编码的美好一天!

翻译自: https://www.freecodecamp.org/news/how-to-minify-images-with-gulp-gulp-imagemin-and-boost-your-sites-performance-6c226046e08e/

gulp-imagemin

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用 `gulp-useref` 并过滤指定 js 文件的示例: ```javascript const gulp = require('gulp'); const useref = require('gulp-useref'); gulp.task('build', function() { return gulp.src('src/*.html') .pipe(useref({ searchPath: ['src', '.'] })) // 过滤掉不需要处理的 js 文件 .pipe(gulp.dest('dist')); }); ``` 在这个示例中,我们使用 `gulp-useref` 来处理 HTML 文件,并将注释块中引用的 JS、CSS 文件合并到一个或多个文件中。同时,我们通过 `searchPath` 属性指定了搜索路径,这样 `gulp-useref` 就能够正确地解析 HTML 文件中的相对路径了。 接着,我们通过 `pipe` 方法将处理后的文件输出到 `dist` 目录中。在这个过程中,我们也可以使用 `gulp-if` 来过滤掉不需要处理的文件。例如,如果我们只想处理所有 `src` 目录下的 JS 文件,可以这样写: ```javascript const gulp = require('gulp'); const useref = require('gulp-useref'); const gulpIf = require('gulp-if'); gulp.task('build', function() { return gulp.src('src/*.html') .pipe(useref({ searchPath: ['src', '.'] })) // 只处理 src 目录下的 js 文件 .pipe(gulpIf('**/*.js', gulp.dest('dist'))) .pipe(gulp.dest('dist')); }); ``` 在这个示例中,我们使用 `gulp-if` 来过滤掉不需要处理的 JS 文件,而只处理 `src` 目录下的 JS 文件。这样,我们就能够只处理我们需要的文件了。 希望这个回答能够帮到你,如果你还有其他问题,可以继续问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值