首先安装npm.
npm init -y
然后安装wordpress/scripts. –save-dev 是写入到package.json
npm install @wordpress/scripts --save-dev
这个会安装很多额外的小包,会花费一点时间。
然后在主题文件夹新建src文件夹。名称必须是src。在src文件夹里新建一个文件,命名为index.js. 在index.js里面复制 jsx 代码。
wp.blocks.registerBlockType("ourblocktheme/banner",{
title:"Banner",
edit:EditComponent,
save:SaveComponent
});
function EditComponent() {
return (
<div className="page-banner">
<div className="page-banner__bg-image"></div>
<div className="page-banner__content container t-center c-white">
<h1 className="headline headline--large">Welcome</h1>
<h2 className="headline headline--medium">We think you’ll like it here.</h2>
<h3 className="headline headline--small">Why don’t you check out the <strong>major</strong> you’re interested in?</h3>
<a href="#" className="btn btn--large btn--blue">Find Your Major</a>
</div>
</div>
)
}
function SaveComponent() {
return <p>This is from our block</p>
}
点击保存。然后告诉wordpress来转换这个jsx文件为可读的js文件。
打开package.json文件,找到scripts命令行,添加build命令:
"build":"wp-scripts build"
然后添加start命令:
"start":"wp-scripts start"
然后保存,万事俱备。build是一次性的重构,start是每次保存时候都自动重构。开发的时候一般都用start
然后在gitbash里或者vscode的terminal里面运行npm run start, (首先要定位到这个文件夹)
然后wp-scripts会自动创建build文件夹。build文件夹里有index.js ,也就是转换过的js文件。也就是转换成wordpress创建block的js的完整写法。
所以我们只要让wordpress来加载build文件夹里的index.js 文件就能执行操作。
然后我们通过wp_enqueue_script加载build文件夹的index.js 到wordpress , 通过enqueue_block_editor_assets钩子加载。就加载进去了block的核心js文件。