diff --git a/packages/uni-cli-shared/__tests__/examples/custom-scripts/package.json b/packages/uni-cli-shared/__tests__/examples/custom-scripts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..868e645958e4725aeb31aef216ea42b0e16d198f --- /dev/null +++ b/packages/uni-cli-shared/__tests__/examples/custom-scripts/package.json @@ -0,0 +1,26 @@ +{ + "uni-app": { + "scripts": { + "H5-WEIXIN": { + "title": "H5-WEIXIN", + "env": { + "UNI_PLATFORM": "H5" + }, + "define": { + "H5-BASE": true, + "H5-WEIXIN": true + } + }, + "H5-QQ": { + "title": "H5-QQ", + "env": { + "UNI_PLATFORM": "H5" + }, + "define": { + "H5-BASE": false, + "H5-QQ": true + } + } + } + } +} diff --git a/packages/uni-cli-shared/__tests__/scripts.spec.ts b/packages/uni-cli-shared/__tests__/scripts.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..0eaa854cd3b500cde68ca7dbd0415f1e47ccb57e --- /dev/null +++ b/packages/uni-cli-shared/__tests__/scripts.spec.ts @@ -0,0 +1,23 @@ +import path from 'path' +import { parseScripts } from '../src/scripts' + +describe('filter', () => { + test(`basic`, () => { + const pkgPath = path.resolve( + __dirname, + 'examples/custom-scripts/package.json' + ) + expect(parseScripts('H5-WEIXIN', pkgPath)).toEqual({ + name: 'H5-WEIXIN', + platform: 'H5', + define: {}, + context: { 'H5-BASE': true, 'H5-WEIXIN': true, 'H5-QQ': false }, + }) + expect(parseScripts('H5-QQ', pkgPath)).toEqual({ + name: 'H5-QQ', + platform: 'H5', + define: {}, + context: { 'H5-BASE': false, 'H5-QQ': true, 'H5-WEIXIN': false }, + }) + }) +}) diff --git a/packages/uni-cli-shared/src/scripts.ts b/packages/uni-cli-shared/src/scripts.ts index 9f7cf1bb2d343dba1159d2dd2a942cee0efa90de..c14eb0fbba8a2c3c87185d74111c08700b3c81b5 100644 --- a/packages/uni-cli-shared/src/scripts.ts +++ b/packages/uni-cli-shared/src/scripts.ts @@ -1,3 +1,4 @@ +import { hasOwn } from '@vue/shared' import fs from 'fs' interface Package { @@ -24,7 +25,8 @@ export function parseScripts(name: string, pkgPath: string) { } const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as Package - const options = pkg['uni-app']?.scripts?.[name] + const scripts = pkg['uni-app']?.scripts || {} + const options = scripts[name] if (!options) { return } @@ -35,10 +37,22 @@ export function parseScripts(name: string, pkgPath: string) { process.exit(0) } const { UNI_PLATFORM, ...define } = options.env + const context = options.define || {} + // 补充当前编译环境未定义的其他编译环境 define + Object.keys(scripts).forEach((scriptName) => { + if (scriptName !== name) { + const scriptDefine = scripts[scriptName].define || {} + Object.keys(scriptDefine).forEach((key) => { + if (!hasOwn(context, key)) { + context[key] = false + } + }) + } + }) return { name: name, platform: UNI_PLATFORM, define, - context: options.define || {}, + context, } }