亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home CMS Tutorial WordPress JavaScript workflow automation with Grunt and Gulp

JavaScript workflow automation with Grunt and Gulp

Aug 29, 2023 pm 09:49 PM
gulp grunt javascript workflow

When you are new to front-end development and start mastering HTML5, CSS, and JavaScript, the obvious next step is The tools in your hand are the most Developers are used to maintaining sanity in this complex space. You deserve more Flexibility and power when writing CSS tables with Less. The same to you It's worth optimizing bandwidth by minifying your JS code. you deserve to be Ability to automatically check if your JS code is good using JSHint.

You deserve these good things.

So you start using all these great tools Manually run more and more command lines. sometimes you forget Run the Less compiler...sometimes you forget to run JSHint and you get errors...

Suddenly you find yourself thinking: Is there a solution to automate all these tools? How can you create a Repeatable workflow to prevent you from making mistakes?

Apparently a solution exists, and there are two tools In particular waiting for you to start using: Grunt and Gulp.

As a newbie in using these tools, you Wondering how they work and which one to use, don't you? Well, that's perfect, You are reading the right article!

1.Example we will use

I will give you the basics of using Grunt and Gulp using a very simple example that you can download from GitHub.

This is a simple website consisting of three parts document:

JavaScript workflow automation with Grunt and Gulp

Styles.less defines CSS tables in a A richer way than using standard CSS files. Finally we use Less compiler creates styles.css document. Using Less, we can use variables in CSS files:

JavaScript workflow automation with Grunt and Gulp

Get more information about Less in this getting started guide.

JavaScript and HTML code do simple. The page should look like this:

JavaScript workflow automation with Grunt and Gulp

2. Understanding Node.js Package Manager

You need to first understand how the Node.js package manager (npm) works.

Npm is a tool that comes with Node.JS. it Used to obtain tools and frameworks while automatically parsing them Dependencies.

For example, use Less and compile it To web-ready CSS files, you first need to install Less using the following command:

npm install -g less

Notice: To get the npm command line, you Node.js must be installed from the Node website.

Once completed, you can run this command Compile .less files to .css:

lessc styles.less > styles.css

Npm uses the file it creates and stores in the local folder where it is working: package.json. This file uses JavaScript Object Notation (JSON) format to let npm know Which tool, version, and current project are installed (use current folder).

This file is important for Grunt and Gulp Because it will contain a list of plugins that have been downloaded and can be used in your application Automate workflows.

To create an empty package.json file, you You can use the following npm commands:

npm init

You will answer some questions You can answer using the default options and then you are good to go.

In this file you will have two Dependencies:

  • needed Execute your web application or Node.js application
  • needed Development stage (like Less), used to compile or check code

Npm basically provides you with three methods Installation package:

  • Use globally on your machine –g or -global option
  • For execution purposes, locally Use no options in your project folder (just use npm install [tools or framework])
  • For development purposes, local Use the project folder of --save-dev Options

The third one will create a devDependencies section/property in the package.json file.

JavaScript workflow automation with Grunt and Gulp

3. Grunt

What Is it Gulu?

Grunt is a pioneer in JavaScript automation Workflow area. There are many well-known Grunt users such as Twitter, jQuery and Modernizr.

The basic principle of Grunt is to provide us with an easy way to run tasks. A task is a set of code files and the configuration files already created for you. You can get new tasks by Install the Grunt plugin obtained using npm. You can find a plugin Pretty much every tool you might use, like Less and JSHint.

要運(yùn)行 Grunt,您必須創(chuàng)建一個(gè) Gruntfile,在其中指定 您要運(yùn)行哪些任務(wù)以及每個(gè)任務(wù)的配置。一旦這個(gè) 完成后,您只需運(yùn)行 grunt 命令行指定要運(yùn)行的任務(wù)(默認(rèn)或特定任務(wù)) 它會自動完成。

現(xiàn)在讓我們通過分步指南來完成這一切設(shè)置。

步驟 1. 創(chuàng)建 Package.json 文件

使用 npm 初始化文件:

npm init

您必須回答一些問題,例如項(xiàng)目名稱和 默認(rèn)的 .js 文件是什么。您也可以選擇手動創(chuàng)建文件 并將其內(nèi)容設(shè)置為:

{

  "name": "project-name",

  "devDependencies": {},

  "dependencies": {}

}

步驟 2. 安裝 Grunt 全球和本地

您需要全局安裝 Grunt 才能獲取命令行并 在本地初始化項(xiàng)目所需的一切。

運(yùn)行:

npm install -g grunt

然后在本地運(yùn)行:

npm install grunt --save-dev

注意: Do not forget the –dev 部分,將其指定為 devDependencies 中的 package.json 文件之一。

步驟 3. 創(chuàng)建 GruntFile.js

Grunt 使用名為 gruntFile.js 的文件進(jìn)行工作。該文件包含 Grunt 所需的一切,也就是說:

  • 配置 任務(wù)
  • custom 任務(wù)
  • 任務(wù)加載

Grunt 希望文件導(dǎo)出一個(gè)需要一個(gè)函數(shù)的函數(shù) 名為“grunt”的參數(shù)。您將使用此對象執(zhí)行所有 Grunt 相關(guān)操作 行動。

這是一個(gè)最小的 gruntfile,僅讀取 package.json 文件 并創(chuàng)建一個(gè) default 任務(wù),該任務(wù)不運(yùn)行任何內(nèi)容。

注意: 將該文件與 package.json 文件并排放置在項(xiàng)目文件夾中。

module.exports = function(grunt) {



  // Project configuration.

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

  });



  // Default task(s).

  grunt.registerTask('default', []);



};?

您可以執(zhí)行它以確保一切都已配置 正確。

為此,請?jiān)陧?xiàng)目上打開命令提示符 文件夾并運(yùn)行:

grunt

您應(yīng)該看到類似這樣的內(nèi)容:

JavaScript workflow automation with Grunt and Gulp

第 4 步:添加您的第一個(gè) 任務(wù):JSHint

現(xiàn)在您的 Gruntfile 已準(zhǔn)備就緒,下一步是添加插件 并使用它。所有插件都可以在 Grunt 網(wǎng)站的列表中找到。中的一個(gè) Gruntfile 中執(zhí)行的常見任務(wù)是檢查 JavaScript 語法是否正確 正確的。為此,我們通常使用 JSHint。

讓我們將其添加到您的 grunt 工作流程中。

如果你在 grunt 插件頁面搜索 JSHint,你會發(fā)現(xiàn) grunt-contrib-jshint,其中 對應(yīng)我們所需要的!

在項(xiàng)目文件夾中,運(yùn)行:

npm install grunt-contrib-jshint --save-dev

完成后,您必須將其添加到 Gruntfile.js 中。那里 有兩個(gè)簡單的步驟:

  1. 加載插件。
  2. 配置 任務(wù)。

要加載插件,請使用 loadNpmTasks 功能:

// Load the plugin that provides the "jshint" task

grunt.loadNpmTasks('grunt-contrib-jshint');

的 配置是在initConfig 函數(shù)中完成的 您必須向參數(shù)中給定的對象添加新屬性。這 必須是您要添加的任務(wù)的名稱并且與插件相關(guān) 你用。了解該名稱和可用選項(xiàng)列表的最佳方式 任務(wù)是查看插件文檔。你總會找到一個(gè) 詳細(xì)記錄的示例。

例如,在 在我們的示例中,我們想要檢查除 gruntfile.js 之外的所有 JavaScript 文件。 我們還希望激活一組規(guī)則來簽入 JavaScript 文件,例如 eqeqeq?以確保我們在需要時(shí)使用三等號。

這是 initConfig 函數(shù)修改:

JavaScript workflow automation with Grunt and Gulp

您可以使用 以下命令行(您將任務(wù)名稱指定為 grunt 的參數(shù)):

grunt jshint

的 result is here:

JavaScript workflow automation with Grunt and Gulp

您只需運(yùn)行該命令即可 遇到任何錯誤都會自動提示您。

恭喜,您現(xiàn)在已經(jīng)在 grunt 中自動執(zhí)行了一項(xiàng)任務(wù) 工作流程!

步驟 5. 添加第二個(gè)任務(wù): 減少編譯

您的 JSHint 任務(wù)運(yùn)行良好,但在 工作流程。通常,我們使用 Grunt 等工具來運(yùn)行多個(gè)任務(wù)。

添加更多內(nèi)容非常容易,因?yàn)槟恍枳裱纯? 相同的步驟。假設(shè)您現(xiàn)在想要添加 less 的編譯 自動化流程中的文件。如果你在 Grunt 插件中搜索,你會 找到一個(gè)可以安裝在項(xiàng)目文件夾中的 grunt-contrib-less 插件:

npm install grunt-contrib-less --save-dev

與 JSHint 任務(wù)一樣,您必須添加 配置:

JavaScript workflow automation with Grunt and Gulp

的n, load the task:

JavaScript workflow automation with Grunt and Gulp

您現(xiàn)在可以運(yùn)行 Grunt 并指定 less 任務(wù):這將僅啟動 Less。 沒關(guān)系,但是您想運(yùn)行所有任務(wù),對吧?這就是 default 任務(wù)的作用。

當(dāng)你只運(yùn)行 grunt 而不指定任何任務(wù)時(shí),它將搜索 default 任務(wù)并運(yùn)行其數(shù)組中指定的所有任務(wù)。您可以修改它以運(yùn)行 lessjshint注意 that to add a group of tasks like default, you need to call the registerTask 功能:

JavaScript workflow automation with Grunt and Gulp

從現(xiàn)在開始,當(dāng)您運(yùn)行 grunt 時(shí),它將運(yùn)行 jshint,然后是 less:

JavaScript workflow automation with Grunt and Gulp

您可以添加任何您想要的任務(wù),并且您可以 還指定其他任務(wù)組,例如 default 并通過將名稱作為參數(shù)傳遞給 grunt 命令行來調(diào)用它們。

簡單吧?

第 6 步:使用“Watch So You Do” 不必手動運(yùn)行 Grunt

現(xiàn)在,您是一名快樂的開發(fā)人員。你所有的重復(fù)性任務(wù)都是 在 grunt 工作流程中實(shí)現(xiàn)自動化,您只需運(yùn)行 grunt 即可 執(zhí)行。但它可以更容易地完成。它可以自動完成。

為此,您可以添加名為 watch 的特定任務(wù)。此任務(wù)將不斷檢查您的工作文件夾,并且, 根據(jù)規(guī)則,當(dāng)文件被修改時(shí),grunt 將運(yùn)行關(guān)聯(lián)的任務(wù)。

首先,在項(xiàng)目文件夾中安裝 watch

npm install grunt-contrib-watch --save-dev

使用 loadNpmTasks 函數(shù)像所有其他任務(wù)一樣加載它,并配置它。配置部分有點(diǎn) 此處有所不同,因?yàn)槟枰獮槊總€(gè)任務(wù)指定配置 想要使用 watch 進(jìn)行覆蓋。

JavaScript workflow automation with Grunt and Gulp

有關(guān)詳細(xì)信息,您可以閱讀此任務(wù)的完整文檔。

當(dāng)您想激活watch時(shí),只需運(yùn)行以下命令:

grunt watch

并且每次打開文件時(shí)都會執(zhí)行任務(wù) 已更改,并且此文件位于特定的監(jiān)視文件范圍內(nèi) 任務(wù)。

JavaScript workflow automation with Grunt and Gulp

就是這樣!你現(xiàn)在知道了要創(chuàng)造的一切 使用 grunt 實(shí)現(xiàn)自動化工作流程。

4. 咕嚕咕嚕

什么 是 Gulp 嗎?

Gulp 是 grunt 的替代品。它是一個(gè) 更新一點(diǎn),并且比 grunt 更靈活而聞名。前 選擇您要使用的一個(gè)后,讓我們看看 gulp 是如何工作的。

Gulp 是一個(gè)工作流程 自動化工具。與 grunt 一樣,它使用 npm 和 package.json 文件工作。全部可用 插件也將使用 npm 下載并添加為 devDependencies 在 package.json 文件。

主要區(qū)別之一是 Gulp 使用流。流是一組函數(shù),文件通過這些函數(shù) 進(jìn)入并在內(nèi)存中進(jìn)行修改。這 文件只會在進(jìn)程結(jié)束時(shí)才會寫入磁盤,所以它更 高效的。另一方面,Grunt 任務(wù)作為孤島工作,無法鏈接。

讓我們快速了解一下 Gulp 的工作原理: 遵循幾個(gè)簡單的步驟。

步驟 1. 創(chuàng)建 Package.json 文件

與 Grunt 類似,你首先 必須創(chuàng)建 package.json 文件。您可以使用與您完全相同的技術(shù) 用于 grunt 示例。

步驟 2. 安裝 Gulp 并 Gulp-Util 全球和本地

創(chuàng)建 package.json 文件后,全局安裝 gulp 并 本地使用:

npm install -g gulp

npm install gulp --save-dev

這將安裝 gulp 命令行以及所需的一切 運(yùn)行 gulp 工作流程。

然后您必須安裝 gulp utils,其中包含其他插件共享的常用功能:

npm install gulp-util --save-dev

最后,創(chuàng)建最小的 gulp 文件,如下所示:

JavaScript workflow automation with Grunt and Gulp

As you can see, it's a bit different from grunt syntax. exist gulp, plugins are loaded using the require syntax, like you may be used to You are a Node.js developer. There is also a default task defined using the gulp.task function.

If you run the gulp command Use the command prompt line in the project folder and you should see results similar to this:

JavaScript workflow automation with Grunt and Gulp

Step 3. Use your first Task: Reduce compilation

To use plugins in gulp you can use the same function as ours Used to create default tasks. This is because you don't have to use a specific name to create the task. you Just call gulp.task, set the name you want, and assign it a JavaScript function as shown below The second parameter. When gulp runs a task, it runs this function.

To use a plugin, you call it with a name of your choice when needed. Usually you call it Part of the streaming workflow that usually starts with selecting a file. This is done via gulp.src Function. It will select a bunch of files and return a stream that can be used By using another function of pipe. That This is how you chain multiple operations without writing them to disk. you Just pass the stream from one plugin to another.

This is a basic example of Less:

JavaScript workflow automation with Grunt and Gulp

We first require ('gulp-less') Load less plugin for gulp. (We get it using npm install gulp-less --save-dev).

的n gulp.src will To select all .less files, we Pass it "pipeline" to the less() function and It is eventually "piped" to gulp.dest Indicates where to write results. Since gulp.src can select multiple files, gulp.dest specifies a folder.

Once you understand the pipeline model, you can easily achieve the same results The result is what we get using grunt.

The power of gulp is that you can create custom tasks in which you Call multiple plugins where you can relate them the way you want.

Note: there is obviously There is also a gulp-watch plugin you can use Automate your workflow!

Conclusion: Which one to choose?

Hope you now have a clearer understanding Learn why you need to automate your workflow and how to get it using Grunt or Gulp.

Choose one of them to update with The task you want to achieve.

Grunt is easy to use. you should not Understanding piping systems makes completing simple tasks easier straightforward. This is a very mature tool used by many well-known editors and developers, and there are many plugins available.

In other words, the way Gulp is designed Can give you a lot of flexibility. It's been around for quite some time, and Even if you can’t find as many plugins as Grunt, all the classic plugins Some are available for Gulp.

If you are using a truly standard workflow Grunt is a good choice for common steps like JSHint, uglifying, CSS validation, etc. choose. If you're doing more complex tasks, Gulp would be a great wingman.

More information

    Grunt website
  • Gulp Website
  • Using Grunt in Microsoft Visual Studio
More JavaScript practices

Microsoft has a lot of free learning about many open source JavaScripts theme, our mission is to create more with Microsoft edge. here has Something worth checking out:

    Microsoft Edge Web Summit 2015 (a complete series on what to expect in new browsers, new web Platform features and speakers from the community)
  • Best //BUILD/ and Windows 10 (including new JavaScript engine for websites and apps)
  • Advancing JavaScript Not breaking the network (Christian Heilmann’s recent keynote)
  • Hosting web applications and the web Platform Innovation (deep dive into topics like manifest.JS)
  • Practical performance tips to make your HTML/JavaScript faster (seven parts) Series (from responsive design to casual games to performance optimization)
  • Get started quickly with modern web platforms (HTML, CSS, and JavaScript)
There are also some free getting started tools: Visual Studio Code, Azure Trial and cross-browser Testing tools – all available for Mac, Linux or Windows.

This article is part of Microsoft's Web Development Technologies series. yes I'm excited to share with you Microsoft Edge and the new EdgeHTML The rendering engine is with you. Get a free virtual machine or run it on your Mac, iOS, Android or Windows devices @ http://dev.modern.ie/.

The above is the detailed content of JavaScript workflow automation with Grunt and Gulp. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to add custom rewrite rules How to add custom rewrite rules Jul 08, 2025 am 12:11 AM

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

How to profile WordPress performance How to profile WordPress performance Jul 07, 2025 am 12:43 AM

1. Use performance analysis plug-in to quickly locate problems. For example, QueryMonitor can view the number of database queries and PHP errors, BlackboxProfiler generates function execution reports, and NewRelic provides server-level analysis; 2. Analyzing PHP execution performance requires checking time-consuming functions, debugging tools usage and memory allocation, such as Xdebug generates flame graphs to assist in optimization; 3. Monitor database query efficiency can be checked through slow query logs and index checks, QueryMonitor can list all SQL and sort by time; 4. Combining external tools such as GooglePageSpeedInsights, GTmetrix and WebPageTest to evaluate front-end plus

See all articles