博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Gulp更快地开发WordPress主题
阅读量:2507 次
发布时间:2019-05-11

本文共 14843 字,大约阅读时间需要 49 分钟。

This Gulp article is part of a series created in partnership with . Thank you for supporting the partners who make SitePoint possible.

该Gulp文章是与合作创建的系列文章的一部分。 感谢您支持使SitePoint成为可能的合作伙伴。

WordPress’ simple theme development is partly responsible for its success. A developer with front-end and PHP knowledge can consult the excellent and get started on their next masterpiece.

WordPress的简单主题开发是其成功的部分原因。 具有前端和PHP知识的开发人员可以咨询优秀的并开始他们的下一个杰作。

Theme development is possible with just a text editor and graphics package, but modern toolsets can revolutionize your workflow. In this tutorial we’ll use to run tasks including:

仅通过文本编辑器和图形包就可以进行主题开发,但是现代工具集可以彻底改变您的工作流程。 在本教程中,我们将使用运行任务,包括:

  • copying newer PHP theme files

    复制较新PHP主题文件
  • optimizing images

    优化图像
  • compiling into a single, minified CSS file

    将编译为单个缩小CSS文件

  • merging ordered JavaScript files, remove debugging statements and minifying

    合并有序JavaScript文件,删除调试语句并缩小
  • automatically refreshing the browser when files are updated.

    文件更新时自动刷新浏览器。

什么是Gulp? (What is Gulp?)

Gulp is a JavaScript-based build system which takes your source files and transforms them into optimized versions. If you’re new to Gulp, please refer to for full installation and usage instructions. A summary of the initial steps:

Gulp是一个基于JavaScript的构建系统,它将获取您的源文件并将其转换为优化版本。 如果您不 Gulp,请参阅获取完整的安装和使用说明。 初始步骤摘要:

  1. Install .

    安装

  2. Install Gulp globally: npm install gulp-cli -g

    全局安装Gulp: npm install gulp-cli -g

  3. Create a project folder and navigate into it: mkdir mytheme followed by cd mytheme.

    创建一个项目文件夹并浏览到其中: mkdir mytheme然后是cd mytheme

  4. Initialize your project with npm: npm init

    使用npm初始化您的项目: npm init

您的项目文件 (Your Project Files)

A Gulp (or any) build process requires a set of original source files containing your unmodified code and images. These are processed, manipulated and minified to create build files.

Gulp(或任何一个)构建过程需要一组原始文件,其中包含您未修改的代码和图像。 对这些文件进行处理,操作和缩小以创建构建文件。

WordPress is installed to a web server folder, perhaps /var/www/ on a Linux/Apache installation. Your WordPress theme must be defined in its own sub-folder within /wp-content/themes/. Therefore, the folder containing our built files could be /var/www/wp-content/themes/mytheme/. At a minimum, themes require two files:

WordPress已安装到Web服务器文件夹,在Linux / Apache安装中可能是/var/www/ 。 您的WordPress主题必须在/wp-content/themes/中的自己的子文件夹中定义。 因此,包含我们构建的文件的文件夹可能是/var/www/wp-content/themes/mytheme/ 。 主题至少需要两个文件:

  • a style.css stylesheet containing meta-data in comments at the top, and

    一个style.css样式表,在顶部的注释中包含元数据,以及

  • an index.php template file.

    index.php模板文件。

Most themes contain many more files for presenting posts, pages, indexes, categories, tags, and errors. Cross-page partials such as headers and footers are usually defined as are image and JavaScript files.

大多数主题包含更多文件,用于显示帖子,页面,索引,类别,标签和错误。 跨页部分(例如页眉和页脚)通常定义为图像和JavaScript文件。

You could place your source files somewhere within the mytheme folder. That may be useful if you’re distributing a theme to be downloaded, modified and built by others. However, for the purpose of this tutorial, we’re going to use a source folder which is inaccessible from the web server, e.g. ~/mytheme/. The benefits of this approach:

您可以将源文件放在mytheme文件夹中的某个位置。 如果您要分发主题以供他人下载,修改和构建,这可能会很有用。 但是,出于本教程的目的,我们将使用无法从Web服务器访问的源文件夹,例如~/mytheme/ 。 这种方法的好处:

  1. Your theme source files can be managed in a single folder and repository without polluting the build or WordPress folders.

    您的主题源文件可以在一个文件夹和存储库中进行管理,而不会污染构建或WordPress文件夹。

  2. The final built theme folder contains only the files it requires.

    最终构建的主题文件夹仅包含其所需的文件。
  3. Gulp, its plug-ins and other applications are not contained in the theme folder. They cannot be accidentally copied to a production server which is unnecessary and could have security implications.

    Gulp,其插件和其他应用程序不包含在主题文件夹中。 不能将它们意外复制到生产服务器上,这是不必要的,并且可能会带来安全隐患。

The source project folder requires a further four sub-folders:

源项目文件夹还需要四个子文件夹:

  • template – the WordPress PHP theme files

    template – WordPress PHP主题文件

  • images – images used by your theme

    images –主题使用的图像

  • scss – Sass SCSS source files

    scss – Sass SCSS源文件

  • js – any number of separate client-side JavaScript source files.

    js –任意数量的单独的客户端JavaScript源文件。

安装依赖项 (Install Dependencies)

From the source folder (~/mytheme/), run the following npm command to install Gulp and all plug-ins as development dependencies:

在源文件夹( ~/mytheme/ )中,运行以下npm命令以安装Gulp和所有插件作为开发依赖项:

npm install --save-dev autoprefixer browser-sync css-mqpacker cssnano gulp gulp-concat gulp-deporder gulp-imagemin gulp-newer gulp-postcss gulp-sass gulp-strip-debug gulp-uglify gulp-util postcss-assets

A node_modules folder will be created which contains the module code. That should be omitted from your source control system (for Git users, add node_modules to your .gitignore file).

将创建一个node_modules文件夹,其中包含模块代码。 这应该从您的源代码管理系统中省略(对于Git用户,将node_modules添加到您的.gitignore文件中)。

创建一个Gulp配置文件 (Create a Gulp Configuration File)

Create a new gulpfile.js configuration file in the root of your source folder. Add this code to get started:

在源文件夹的根目录中创建一个新的gulpfile.js配置文件。 添加以下代码即可开始:

// Gulp.js configuration'use strict';const  // source and build folders  dir = {    src         : 'src/',    build       : '/var/www/wp-content/themes/mytheme/'  },  // Gulp and plugins  gulp          = require('gulp'),  gutil         = require('gulp-util'),  newer         = require('gulp-newer'),  imagemin      = require('gulp-imagemin'),  sass          = require('gulp-sass'),  postcss       = require('gulp-postcss'),  deporder      = require('gulp-deporder'),  concat        = require('gulp-concat'),  stripdebug    = require('gulp-strip-debug'),  uglify        = require('gulp-uglify');// Browser-syncvar browsersync = false;// PHP settingsconst php = {  src           : dir.src + 'template/**/*.php',  build         : dir.build};// copy PHP filesgulp.task('php', () => {  return gulp.src(php.src)    .pipe(newer(php.build))    .pipe(gulp.dest(php.build));});

We’re defining our default folders, loading modules, then creating a php task to copy new and updated files to the theme folder. The task has been kept intentionally simple to copy the PHP source files as-is.

我们先定义默认文件夹,加载模块,然后创建一个php任务,将新文件和更新文件复制到主题文件夹。 该任务被故意简化为按原样复制PHP源文件。

Save gulpfile.js and create a few .php files in the source template folder. Then enter the following command:

保存gulpfile.js并在源template文件夹中创建一些.php文件。 然后输入以下命令:

gulp php

All the files will be copied to the theme folder (/var/www/wp-content/themes/mytheme/).

所有文件都将复制到主题文件夹( /var/www/wp-content/themes/mytheme/ )。

图像处理 (Image Processing)

Image files can often be compressed further using tools such as . Add the following code to gulpfile.js:

通常可以使用诸如工具进一步压缩图像文件。 将以下代码添加到gulpfile.js

// image settingsconst images = {  src         : dir.src + 'images/**/*',  build       : dir.build + 'images/'};// image processinggulp.task('images', () => {  return gulp.src(images.src)    .pipe(newer(images.build))    .pipe(imagemin())    .pipe(gulp.dest(images.build));});

Save then run gulp images. Compressed versions of any new or updated images in the source images folder are copied to /var/www/wp-content/themes/mytheme/images/.

保存然后运行gulp images 。 源images文件夹中任何新图像或更新图像的压缩版本都复制到/var/www/wp-content/themes/mytheme/images/

Sass编译 (Sass Compilation)

WordPress cannot use Sass files directly; you must compile to a single style.css file. Add the following code to gulpfile.js:

WordPress无法直接使用Sass文件; 您必须编译为单个style.css文件。 将以下代码添加到gulpfile.js

// CSS settingsvar css = {  src         : dir.src + 'scss/style.scss',  watch       : dir.src + 'scss/**/*',  build       : dir.build,  sassOpts: {    outputStyle     : 'nested',    imagePath       : images.build,    precision       : 3,    errLogToConsole : true  },  processors: [    require('postcss-assets')({      loadPaths: ['images/'],      basePath: dir.build,      baseUrl: '/wp-content/themes/wptheme/'    }),    require('autoprefixer')({      browsers: ['last 2 versions', '> 2%']    }),    require('css-mqpacker'),    require('cssnano')  ]};// CSS processinggulp.task('css', ['images'], () => {  return gulp.src(css.src)    .pipe(sass(css.sassOpts))    .pipe(postcss(css.processors))    .pipe(gulp.dest(css.build))    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());});

Launch this new task with gulp css to:

使用gulp css启动此新任务以:

  • run the Gulp images task first (images may be required in your CSS)

    首先运行Gulp images任务(CSS中可能需要图片)

  • compile the Sass code in the source scss/style.scss file using the fast compiler

    使用快速的编译器在源scss/style.scss文件中编译Sass代码

  • use to automatically add asset references, apply vendor prefixes, pack media queries together, and minify the resulting CSS code

    使用自动添加资产引用,应用供应商前缀,将媒体查询打包在一起并最小化生成CSS代码

  • output the stylesheet to /var/www/wp-content/themes/mytheme/style.css.

    将样式表输出到/var/www/wp-content/themes/mytheme/style.css

  • force a CSS reload (more about that later).

    强制重新加载 CSS(稍后会详细介绍)。

The source scss/style.scss file must include the WordPress theme meta data at the top, e.g.

scss/style.scss文件必须在顶部包含WordPress主题元数据,例如

/*!    Theme Name: My Theme    Theme URI: https://www.sitepoint.com/    Description: Demonstration theme    Version: 1.0.0    Author: Craig Buckler (@craigbuckler)    Author URI: https://www.sitepoint.com/    Tags: Gulp    License: MIT    License URI: http://opensource.org/licenses/mit-license.php*/@import '_base';@import '_forms';@import '_tables';@import 'components/_widget1';// etc...

It is important to use /*! as the first line. This ensures the minifier does not remove the comment and render your theme unusable.

使用/*!很重要/*! 作为第一行。 这样可以确保压缩程序不会删除注释并使主题无法使用。

The plugin allows you to refer to image assets using code such as:

插件允许您使用以下代码引用图像资产:

.widget1 {  width: width('myimage.jpg');  height: height('myimage.jpg');  background-image: resolve('myimage.jpg');}

You can also inline images with automatic Base64 encoding:

您还可以使用自动Base64编码内嵌图像:

.widget2 {  background-image: inline('myimage.jpg');}

JavaScript处理 (JavaScript Processing)

Add the following code to gulpfile.js:

将以下代码添加到gulpfile.js

// JavaScript settingsconst js = {  src         : dir.src + 'js/**/*',  build       : dir.build + 'js/',  filename    : 'scripts.js'};// JavaScript processinggulp.task('js', () => {  return gulp.src(js.src)    .pipe(deporder())    .pipe(concat(js.filename))    .pipe(stripdebug())    .pipe(uglify())    .pipe(gulp.dest(js.build))    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());});

Run this new task with gulp js to:

使用gulp js运行此新任务以:

  • process all JavaScript files in the source js folder

    处理源js文件夹中的所有JavaScript文件

  • order the files appropriately. Add comments at the top of your JavaScript files to declare dependencies, e.g. // requires: lib1.js or // requires: config.js lib1.js.

    适当地订购文件。 在JavaScript文件顶部添加注释以声明依赖关系,例如// requires: lib1.js// requires: config.js lib1.js

  • concatenate into a single file

    连接成一个文件
  • strip all debugging and console logging statements

    剥离所有调试和控制台日志记录语句
  • minify the code

    减少代码
  • output the resulting code to /var/www/wp-content/themes/mytheme/js/scripts.js.

    将结果代码输出到/var/www/wp-content/themes/mytheme/js/scripts.js

  • force a CSS reload (more about that later).

    强制重新加载 CSS(稍后会详细介绍)。

运行一切 (Run Everything)

Rather than calling each task separately, we can add the following code to gulpfile.js:

我们可以将以下代码添加到gulpfile.js ,而不是分别调用每个任务:

// run all tasksgulp.task('build', ['php', 'css', 'js']);

You can now use gulp build to run the php, js, css and images tasks in parallel. (Note images is a dependency of the css task so we need not call it directly.)

现在,您可以使用gulp build来并行运行phpjscssimages任务。 (请注意, imagescss任务的依赖项,因此我们无需直接调用它。)

启用文件监视和Browsersync (Enable File Watching and Browsersync)

Your workflow can be radically improved by:

您可以通过以下方法从根本上改善您的工作流程:

  1. Letting Gulp watch for file changes before launching the appropriate task.

    让Gulp在启动适当的任务之前监视文件更改。
  2. Automatically reloading CSS and JavaScript files when they change (without a page refresh).

    更改CSS和JavaScript文件时自动重新加载(无需刷新页面)。
  3. Automatically refreshing the page when a template file changes.

    模板文件更改时自动刷新页面。

First, we need to define a browsersync task in gulpfile.js. This will create a proxy server to your web server running WordPress on localhost (change this domain or use an IP address as necessary):

首先,我们需要在gulpfile.js定义一个browsersync任务。 这将为在localhost上运行WordPress的Web服务器创建代理服务器(更改此域或根据需要使用IP地址):

// Browsersync optionsconst syncOpts = {  proxy       : 'localhost',  files       : dir.build + '**/*',  open        : false,  notify      : false,  ghostMode   : false,  ui: {    port: 8001  }};// browser-syncgulp.task('browsersync', () => {  if (browsersync === false) {    browsersync = require('browser-sync').create();    browsersync.init(syncOpts);  }});

Now add a watch task to run Browsersync, watch for file changes and run the appropriate task:

现在添加watch任务以运行Browsersync,监视文件更改并运行适当的任务:

// watch for file changesgulp.task('watch', ['browsersync'], () => {  // page changes  gulp.watch(php.src, ['php'], browsersync ? browsersync.reload : {});  // image changes  gulp.watch(images.src, ['images']);    // CSS changes  gulp.watch(css.watch, ['css']);  // JavaScript main changes  gulp.watch(js.src, ['js']);});

Finally, add a default Gulp task which runs an initial build and starts the watch task:

最后,添加一个default Gulp任务,该任务将运行初始构建并启动watch任务:

// default taskgulp.task('default', ['build', 'watch']);

Now run gulp from the command line. The console will display output which includes lines similar to:

现在从命令行运行gulp 。 控制台将显示包含类似于以下内容的行的输出:

[BS] Proxying: http://localhost[BS] Access URLs: -------------------------------------       Local: http://localhost:3000    External: http://192.168.1.99:3000 -------------------------------------          UI: http://localhost:8001 UI External: http://192.168.1.99:8001 -------------------------------------[BS] Watching files...

Rather than loading your development site from http://localhost/, enter the address http://localhost:3000/ or the External URL if you are viewing from another device. Your WordPress site will load as before but Gulp will watch for changes and apply the updates immediately. You’ll need never switch to your browser and click refresh again!

而不是从http://localhost/加载开发站点,如果要从另一台设备查看,请输入地址http://localhost:3000/外部 URL。 您的WordPress网站将像以前一样加载,但是Gulp将监视更改并立即应用更新。 您无需切换到浏览器,然后再次单击刷新!

Hit Ctrl/Cmd + C when you want to stop Gulp processing.

要停止Gulp处理时,请按Ctrl / Cmd +C

进一步增强 (Enhance Further)

We’ve covered the basics of WordPress theme development with Gulp but there are to aid your workflow. You could consider additional tasks to:

我们已经用Gulp涵盖了WordPress主题开发的基础知识,但是可以帮助您的工作流程。 您可以考虑其他任务以:

  • lint your and code

    整理您的和代码

  • create from package.json infomation

    package.json信息创建

  • WordPress assets

    WordPress资产

  • automatically deploy your theme to a production server.

    自动将您的主题部署到生产服务器。

A few hours writing Gulp tasks could save many days of manual processing over the long term.

从长远来看,编写Gulp任务几个小时可以节省许多天的人工处理。

翻译自:

转载地址:http://bxegb.baihongyu.com/

你可能感兴趣的文章
AC自动机模板
查看>>
python 基本语法
查看>>
Swift - 点击箭头旋转
查看>>
git配置
查看>>
【hexo】01安装
查看>>
CI框架源码学习笔记2——Common.php
查看>>
005---书籍添加和编辑的提交数据
查看>>
使用case语句给字体改变颜色
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
JSP九大内置对象及四个作用域
查看>>
ConnectionString 属性尚未初始化
查看>>
数据结构-栈 C和C++的实现
查看>>
MySQL基本命令和常用数据库对象
查看>>
poj 1222 EXTENDED LIGHTS OUT(位运算+枚举)
查看>>
进程和线程概念及原理
查看>>
Lucene、ES好文章
查看>>
android 生命周期
查看>>
jquery--this
查看>>
MySQL 5.1参考手册
查看>>