import { spawnSync } from 'node:child_process' import { createRequire } from 'node:module' import { copyFileSync, mkdirSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { environmentNames, outputDirectory, resolveEnvironment } from '../config/environments.ts' const root = fileURLToPath(new URL('..', import.meta.url)) const [command, platform, selectedEnvironment] = process.argv.slice(2) if (!['build', 'watch'].includes(command) || !['weapp', 'h5'].includes(platform)) { console.error('Usage: node scripts/taro.mjs ') process.exit(1) } if (selectedEnvironment === 'all' && command !== 'build') { console.error('The all option is only available for one-off builds.') process.exit(1) } try { const environments = selectedEnvironment === 'all' ? environmentNames : [resolveEnvironment(selectedEnvironment).name] const require = createRequire(import.meta.url) const cli = path.join(path.dirname(require.resolve('@tarojs/cli/package.json')), 'bin/taro') for (const name of environments) { const output = path.join(root, outputDirectory(platform)) // Each mode runs in its own process, so dotenv values cannot leak between builds. const metadataDirectory = path.join(root, '.cache/build', platform, name) const args = [cli, 'build', '--type', platform, '--mode', name, ...(command === 'watch' ? ['--watch'] : [])] console.log(`\n[${name}] ${platform} → ${outputDirectory(platform)}\n`) const result = spawnSync(process.execPath, args, { cwd: root, stdio: 'inherit', env: { ...process.env, APP_ENV: name, NODE_ENV: command === 'watch' ? 'development' : 'production', TARO_ENV: platform }, }) if (result.error) throw result.error if (result.status !== 0) process.exit(result.status ?? 1) mkdirSync(output, { recursive: true }) if (platform === 'weapp') { copyFileSync(path.join(metadataDirectory, 'project.config.json'), path.join(output, 'project.config.json')) } copyFileSync(path.join(metadataDirectory, 'build-info.json'), path.join(output, 'build-info.json')) } } catch (error) { console.error(error instanceof Error ? error.message : error) process.exit(1) }