使用CocosCreator开发面临一个问题,代码保存后需要切换回CocosCreator或者在界面上点击Recompile按钮进行编译,才能查看到最新的效果。为了提升开发效率,可以增加一套自动检测代码变化,并刷新浏览器的机制。
本文中的示例代码只对assets/Script中的文件变化进行监听,并且只有是后缀是.ts文件才会发送接口请求编译。
初始化node环境
首先在cocos项目根目录下,使用npm init初始化环境,一路回车即可
longxiaobodeiMac:GaussCode longxiaobo$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (gausscode)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/longxiaobo/Public/GaussProject/GaussCode/package.json:
{
"name": "gausscode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
longxiaobodeiMac:GaussCode longxiaobo$
安装依赖
使用npm i -D glob chokidar axios在项目目录下,安装监控功能的依赖库
longxiaobodeiMac:GaussCode longxiaobo$ npm i -D glob chokidar axios
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN gausscode@1.0.0 No description
npm WARN gausscode@1.0.0 No repository field.
+ glob@7.1.6
+ axios@0.19.1
+ chokidar@3.3.1
added 30 packages from 31 contributors and audited 37 packages in 17.523s
2 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
longxiaobodeiMac:GaussCode longxiaobo$
编写监控源代码
在项目根目录下新建compile文件,粘贴如下代码
#!/usr/bin/env node
var chokidar = require('chokidar')
var path = require('path')
var axios = require('axios')
// CocosCreator编译接口(等效于界面点击Recompile)
var url = 'http://localhost:7456/update-db'
// 编译标识,防止重复编译
var compling = false
// 通过接口请求CocosCreator编译
function requestForUpdate (path) {
// 如果不是在编译中或者后缀名不是ts的直接跳过
if (compling || path.indexOf('.ts') + 3 !== path.length) return
compling = true
axios.get(url).then(function (res) {
console.info('%s - request for update result = %s', new Date(), res.data)
setTimeout(() => {
compling = false
}, 300)
})
}
// 监听文件夹变化
chokidar.watch(path.join(__dirname, './assets/Script'), {
ignored: /[\/\\]\./,
persistent: true
}).on('change', requestForUpdate)
.on('add', requestForUpdate)
创建批处理命令
把package.json修改为如下
{
"name": "gausscode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node compile"
},
"author": "",
"license": "ISC",
"devDependencies": {
"axios": "^0.19.1",
"chokidar": "^3.3.1",
"glob": "^7.1.6"
}
}
运行命令
在命令行工具中切换到项目根目录,执行node compile
longxiaobodeiMac:GaussCode longxiaobo$ npm run dev
> gausscode@1.0.0 dev /Users/longxiaobo/Public/GaussProject/GaussCode
> node compile
2020-01-15T04:06:07.628Z - request for update result = Changes submitted
该命令开启后,只要ctrl+s保存文件,就会自动编译和刷新浏览器