h5_for_electron.build.win.x64.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // 执行脚本 taro build --type h5 ,并且把环境变量 TARO_API_URL 传递过去
  2. const { execSync } = require('child_process');
  3. const fs = require('fs');
  4. const path = require('path');
  5. function isCI(){
  6. const isCI = process.env.CI === 'true' || !!process.env.GITHUB_ACTIONS;
  7. return isCI;
  8. }
  9. function getGhToken() {
  10. // 1. 在 GitHub Actions 里官方会注入 ACTIONS_RUNTIME_TOKEN 或 CI=true
  11. const isCI = process.env.CI === 'true' || !!process.env.GITHUB_ACTIONS;
  12. if (isCI) {
  13. console.log(`you are running in ic and the GH_token is ${process.env.GH_TOKEN}`)
  14. // CI 环境:直接拿 secret(工作流里必须 env:{GH_TOKEN:${{secrets.GH_TOKEN}}})
  15. const token = process.env.GH_TOKEN;
  16. if (!token) throw new Error('CI 环境缺少 GH_TOKEN,请检查 workflow yaml');
  17. return token;
  18. }
  19. // 2. 本地开发:优先读本地 ~/.gh-token(自己放的),没有再读环境变量,还没有就空
  20. try {
  21. return readFileSync(join(require('os').homedir(), '.gh-token'), 'utf8').trim();
  22. } catch {
  23. return process.env.GH_TOKEN || '';
  24. }
  25. }
  26. const TARO_API_URL = 'http://101.43.219.60:7700'; // 远程地址,这里写死,要做成部署后可配置
  27. const TARO_MQTT_URL ='ws://101.43.219.60:8083/mqtt';
  28. const rootDir = path.join(__dirname, '..'); // 项目根目录
  29. execSync(`npm run build:h5`, { cwd: rootDir, stdio: 'inherit', env: { ...process.env, TARO_API_URL ,TARO_MQTT_URL} }, (error, stdout, stderr) => {
  30. if (error) {
  31. console.error(`Error executing command: ${error.message}`);
  32. return;
  33. }
  34. if (stderr) {
  35. console.error(`Command stderr: ${stderr}`);
  36. return;
  37. }
  38. console.log(`Command stdout: ${stdout}`);
  39. });
  40. function run(cmd,env={}) {
  41. console.log(`\n>>> ${cmd}`);
  42. try {
  43. execSync(cmd, { stdio: 'inherit', cwd: process.cwd() ,env:env});
  44. } catch (e) {
  45. console.error(`命令失败: ${cmd}`, e.message);
  46. exit(1);
  47. }
  48. }
  49. try {
  50. const GH_TOKEN = getGhToken(); // CI/本地 都能拿到合适值
  51. const cmd = isCI()
  52. ? 'npx electron-builder --config electron-builder.json --win --publish always'
  53. : 'npx electron-builder --config electron-builder.json --win ';
  54. execSync(cmd, {
  55. stdio: 'inherit',
  56. cwd: process.cwd(),
  57. env: { ...process.env, GH_TOKEN } // 关键:仅追加 token,其他不动
  58. });
  59. console.log('\n✅ 全部构建完成');
  60. } catch (err) {
  61. console.error('Failed to execute :', err.message);
  62. process.exit(1);
  63. }