WP笔记

如何在WordPress主题中使用webpack

webpack是一款打包工具,可以将一些重复劳动自动化,比如css、js压缩打包,给css的属性添加浏览器前缀,即css vendor prefixes,还可以在css、js文件发生变化时帮我们自动刷新页面,或者允许其它设备访问本地的项目,总之很方便。本文就介绍一个简单的WordPress主题里配置webpack的方法。

准备工作

首先,安装NodeJS,webpack也仅仅是一个package。

本例使用一个storefront主题的子主题进行演示,文件结构如下所示:

assets/
   - src/
       - style.css
       - script.js
   - dist/
   - package.json
   - webpack.config.js
index.php等其它主题默认文件
...

style.css是主题主样式表,script.js则负责所有javascript代码。

开始安装webpack

package.json中写入我们需要安装的packages,在webpack.config.js里写入webpack的配置,例如本地测试地址等等,再运行安装命令就完事了。

package.json的内容:

{
  "name": "My project name",
  "private": true,
  "dependencies": {
    "@babel/polyfill": "^7.11.5"
  },
  "devDependencies": {
    "@babel/cli": "^7.16.0",
    "@babel/core": "^7.16.5",
    "@babel/preset-env": "^7.16.5",
    "babel-core": "^7.0.0-bridge.0",
    "browser-sync": "^2.27.7",
    "browser-sync-webpack-plugin": "^2.3.0",
    "clean-webpack-plugin": "^4.0.0",
    "css-loader": "^6.5.1",
    "css-minimizer-webpack-plugin": "^3.3.1",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^2.4.5",
    "postcss": "^8.4.5",
    "postcss-loader": "^6.2.1",
    "postcss-preset-env": "^7.1.0",
    "sass-loader": "^12.4.0",
    "style-loader": "^3.3.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  },
  "scripts": {
    "prod": "webpack --mode production",
    "dev": "webpack --mode development --watch"
  },
  "babel": {
    "presets": [
      "@babel/preset-env"
    ]
  }
}

webpack.config.js的内容:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin   = require("css-minimizer-webpack-plugin");
const BrowserSyncPlugin    = require('browser-sync-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
var path                   = require('path');

const jsPath      = './assets/src/';
const cssPath     = './assets/src/';
const outputPath  = './assets/dist/';
const localDomain = 'http://localhost/wordpress/';
const entryPoints = {
	'script': jsPath + '/script.js',
	'style': cssPath + '/style.css',
};
module.exports = {
	entry: entryPoints,
	output: {
		path: path.resolve(__dirname, outputPath),
		filename: '[name].js',
	},
	plugins: [
		new MiniCssExtractPlugin({
			filename: '[name].css',
		}),
		new MiniCssExtractPlugin(),
		new BrowserSyncPlugin({
			proxy: localDomain,
			files: [outputPath + '/*.css', outputPath + '/*.js'],
			injectCss: true,
		}, {
			reload: false,
		}),
		new CleanWebpackPlugin(),
	],
	module: {
		rules: [{
				test: /\.s?[c]ss$/i,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			},
			{
				test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
				type: "asset",
			},
		]
	},
	optimization: {
		minimize: true,
		minimizer: [
			// For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
			// `...`,
			new CssMinimizerPlugin(),
		],
	},
};

文件内容搞定后,在主题所在目录打开Windows cmd命令行工具,输入如下命令,进行安装:

npm install
npm install

安装好后,运行如下命令开启测试功能:

npm run dev
npm run dev

如上图所示,Local里的地址是本地测试地址,External是一个可以让其它设备访问本设备站点的地址,方便responsive测试。

用浏览器打开http://localhost:3000/wordpress/,如下

使用webpack开发wordpress主题

当你编辑style.css或者script.js时,网页会自动刷新,多设备还能同步刷新,省了很多时间。

如果要发布产品,则运行

npm run prod

在WordPress主题中引入生成的文件

生成的文件会被放入dist文件夹,则引入的代码如下:

add_action( 'wp_enqueue_scripts', 'sf_child_theme_dequeue_style', 999 );
/**
 * Dequeue the Storefront Parent theme core CSS
 */
function sf_child_theme_dequeue_style() {
  wp_enqueue_style( 'my-theme-css', get_stylesheet_directory_uri() . '/assets/dist/style.css');
  wp_enqueue_style( 'my-theme-js', get_stylesheet_directory_uri() . '/assets/dist/script.js');
}

留言

您的电子邮箱地址不会被公开。