Skip to content

Commit 34c0797

Browse files
committed
feat(harmony): update page tpl
1 parent 88b2828 commit 34c0797

File tree

22 files changed

+217
-135
lines changed

22 files changed

+217
-135
lines changed

packages/taro-platform-harmony-cpp/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"@tarojs/service": "workspace:*",
4848
"@types/react": "^18.3.3",
4949
"@types/react-reconciler": "^0.28.8",
50+
"fast-glob": "^3.3.2",
5051
"json5": "^2.2.3",
5152
"react": "^18.3.1",
5253
"react-dom": "^18.3.1",
@@ -69,7 +70,6 @@
6970
"@tarojs/taro": "workspace:*",
7071
"@tarojs/vite-runner": "workspace:*",
7172
"@types/node": "^18.19.34",
72-
"fast-glob": "^3.3.2",
7373
"postcss": "^8.4.38",
7474
"prettier": "^2.8.8",
7575
"rollup-plugin-copy": "workspace:*",

packages/taro-platform-harmony-cpp/src/index.ts

+26-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
/* eslint-disable no-console */
22
import path from 'node:path'
33

4-
import { chalk, NODE_MODULES } from '@tarojs/helper'
4+
import { chalk, fs, NODE_MODULES, NPM_DIR } from '@tarojs/helper'
55
import { DEFAULT_TERSER_OPTIONS } from '@tarojs/vite-runner/dist/utils/constants'
66

77
import initCommands from './commands'
88
import HarmonyCPP from './program'
9-
import { CPP_LIBRARY_NAME, CPP_LIBRARY_PATH, getProcessArg, PLATFORM_NAME } from './utils'
9+
import { CPP_LIBRARY_NAME, CPP_LIBRARY_PATH, getProcessArg, PLATFORM_NAME, SEP_RGX } from './utils'
1010
import { PKG_DEPENDENCIES, PKG_NAME, PKG_VERSION, PROJECT_DEPENDENCIES_NAME } from './utils/constant'
1111

1212
import type { IPluginContext } from '@tarojs/service'
@@ -29,7 +29,7 @@ export default (ctx: IPluginContext, options: IOptions = {}) => {
2929
opts.ohPackage.dependencies ||= {}
3030

3131
if (options.useChoreLibrary) {
32-
opts.chorePackagePrefix ||= `${PKG_NAME}/src/main/ets/npm`
32+
opts.chorePackagePrefix ||= `${PKG_NAME}/src/main/ets/${NPM_DIR}`
3333
opts.ohPackage.dependencies[PKG_NAME] ||= `^${PKG_VERSION}`
3434
PROJECT_DEPENDENCIES_NAME.forEach(key => {
3535
opts.ohPackage.dependencies[key] ||= PKG_DEPENDENCIES[key]
@@ -72,12 +72,17 @@ export default (ctx: IPluginContext, options: IOptions = {}) => {
7272

7373
if (options.useChoreLibrary === false) {
7474
const { appPath } = ctx.paths
75-
const { outputRoot } = ctx.runOpts.config
75+
const { outputRoot } = config
7676
const npmDir = path.join(outputRoot, NODE_MODULES)
7777
// Note: 注入 C-API 库
7878
program.externalDeps.forEach(([libName, _, target]) => {
7979
program.moveLibraries(target || libName, path.resolve(npmDir, libName), appPath, !target)
8080
})
81+
program.handleResourceEmit(outputRoot, appPath)
82+
program.generateInitialEntry()
83+
if (config.hapName !== 'entry') { // Note: 如果是 entry 不需要重写 BuildProfile 路径
84+
fixBuildProfile(outputRoot, path.join(outputRoot, '../../..'))
85+
}
8186
}
8287
}
8388
})
@@ -102,3 +107,20 @@ function assertHarmonyConfig (ctx: IPluginContext, config): asserts config is IH
102107
throwError('请设置 harmony.projectPath')
103108
}
104109
}
110+
111+
export function fixBuildProfile(lib = '', outputRoot = '') {
112+
const stats = fs.statSync(lib)
113+
if (stats.isDirectory()) {
114+
fs.readdirSync(lib).forEach((item) => fixBuildProfile(path.join(lib, item), outputRoot))
115+
} else if (stats.isFile() && lib.endsWith('.ets')) {
116+
let data = fs.readFileSync(lib, 'utf-8')
117+
const buildProfilePath = path.resolve(outputRoot, 'BuildProfile')
118+
const rgx = /import\s+(\S+)\s+from\s*['"]BuildProfile['"]/
119+
if (rgx.test(data)) {
120+
data = data.replace(rgx, (_, p1) => {
121+
return `import ${p1} from '${path.relative(path.dirname(lib), buildProfilePath).replace(SEP_RGX, '/')}'`
122+
})
123+
fs.writeFileSync(lib, data, 'utf-8')
124+
}
125+
}
126+
}

packages/taro-platform-harmony-cpp/src/program/babel/global.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isLocalPath, parseLocalPath } from '../../utils'
1+
import { isLocalPath, NPM_DIR, parseLocalPath } from '../../utils'
22
import { PKG_NAME } from '../../utils/constant'
33
import { globalVarName, loadLibraryFunctionName, setLibraryFunctionName } from '../template/entry'
44

@@ -24,7 +24,7 @@ export default function transformGlobalModePlugin ({
2424
const importFunc = isGlobal ? `${globalVarName}.${loadLibraryFunctionName}` : loadLibraryFunctionName
2525
const exportFunc = isGlobal ? `${globalVarName}.${setLibraryFunctionName}` : setLibraryFunctionName
2626
const exportPaths: [boolean, ...string[]] = [isGlobal, projectId, fileName]
27-
chorePackagePrefix = chorePackagePrefix || `${PKG_NAME}/src/main/ets/npm`
27+
chorePackagePrefix = chorePackagePrefix || `${PKG_NAME}/src/main/ets/${NPM_DIR}`
2828

2929
return ({ types: t }: typeof BabelCore): BabelCore.PluginObj<BabelCore.PluginPass> => ({
3030
visitor: {

packages/taro-platform-harmony-cpp/src/program/index.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export default class Harmony extends HarmonyOS {
3737
// @ts-ignore
3838
super(ctx, config) // Note: link 时,ctx 类型可能无法对齐,此处忽略类型检查
3939
const that = this
40-
this.externalDeps.push([this.runtimePath, new RegExp(`^${this.runtimePath.replace(/([-\\/$])/g, '\\$1')}$`)])
40+
this.externalDeps.push([this.runtimePath, new RegExp(`^${this.runtimePath.replace(/([-\\/$])/g, '\\$1')}`)])
4141
this.externalDeps.forEach(e => {
4242
if (e[0] === '@tarojs/react') {
4343
e[2] = this.runtimeFrameworkReconciler
@@ -208,9 +208,10 @@ export default class Harmony extends HarmonyOS {
208208
const outputFile = isFile ? outputPath + '.js' : path.join(outputPath, 'index.js')
209209
const needDeclaration = /@tarojs[\\/](runtime|taro)/.test(outputPath)
210210
if (!fs.existsSync(inputPath)) {
211-
await sleep(100)
211+
await sleep(150)
212212
}
213213
try {
214+
fs.ensureDirSync(path.dirname(outputFile))
214215
await generatePackage.call(this, {
215216
input: inputPath,
216217
output: outputFile,
@@ -229,6 +230,9 @@ export default class Harmony extends HarmonyOS {
229230
} catch (error) {
230231
console.error(`移动 ${chalk.yellow(inputPath)}${outputPath} 失败:${error.message}\n`, error.stack) // eslint-disable-line no-console
231232
}
233+
if (!fs.existsSync(outputFile)) {
234+
await sleep(150)
235+
}
232236
// Note: 非 ETS 依赖需要能注入到 JSVM 中
233237
const resourcesFile = outputFile.replace(/[\\/]ets[\\/]/g, '/resources/rawfile/')
234238
fs.moveSync(outputFile, resourcesFile, { overwrite: true })

packages/taro-platform-harmony-cpp/src/program/rollup/global-plugin.ts

+8-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { transformSync } from '@babel/core'
44
import { isFunction } from '@tarojs/shared'
55
import { TARO_COMP_SUFFIX } from '@tarojs/vite-runner/dist/harmony/entry'
66

7-
import { getProjectId, isLocalPath, parseLocalPath, PKG_NAME, PKG_VERSION, SEP_RGX } from '../../utils'
7+
import { getProjectId, isLocalPath, NPM_DIR, PACKAGE_NAME, parseLocalPath, PKG_VERSION, SEP_RGX } from '../../utils'
88
import transformGlobalModePlugin from '../babel/global'
99
import { babelPresets } from '../babel/presets'
1010
import { entryFileName, loadLibraryFunctionName, setLibraryFunctionName } from '../template/entry'
@@ -47,7 +47,7 @@ export function fixImportCode(
4747
if (source.endsWith('.json')) return true
4848
if (source.endsWith(TARO_COMP_SUFFIX)) return true
4949
} else {
50-
if (sourceValue.includes(`${PKG_NAME}/dist/runtime/runtime-harmony`)) return true
50+
if (sourceValue.includes(`${PACKAGE_NAME}/dist/runtime/runtime-harmony`)) return true
5151
}
5252
}
5353
})
@@ -99,16 +99,15 @@ export default function (this: Harmony | void, opt: IPluginOption = {}): PluginO
9999
const { taroConfig, cwd: appPath } = compiler
100100
const { sourceRoot = 'src' } = taroConfig
101101
const projectId = moduleId || getProjectId(taroConfig?.projectName)
102-
const chorePackagePrefix = runOpts?.config.chorePackagePrefix
103102
const sourcePath = path.posix.join(appPath, sourceRoot)
104103

105104
if (compiler) {
106105
compiler.loaderMeta ||= {}
107106
compiler.loaderMeta.enableParseJSXStyle = true
108107
}
109108

110-
if (!isPureComp && compiler?.components instanceof Array) {
111-
compiler.components.forEach((config: TaroHarmonyPageMeta) => {
109+
if (!isPureComp) {
110+
const modifyPageOrComp = (config: TaroHarmonyPageMeta) => {
112111
const oddModifyPageImport = config.modifyPageImport
113112
config.modifyPageImport = function (this: PageParser, importStr: string[], page: TaroHarmonyPageMeta) {
114113
if (isFunction(oddModifyPageImport)) {
@@ -120,13 +119,15 @@ export default function (this: Harmony | void, opt: IPluginOption = {}): PluginO
120119
}
121120

122121
fixImportCode(importStr, {
123-
chorePackagePrefix,
122+
chorePackagePrefix: runOpts?.config.chorePackagePrefix ?? path.relative(path.dirname(page.name), NPM_DIR),
124123
projectId,
125124
sourcePath,
126125
fileName: page.name,
127126
})
128127
}
129-
})
128+
}
129+
compiler?.pages?.forEach?.(modifyPageOrComp)
130+
compiler?.components?.forEach?.(modifyPageOrComp)
130131
}
131132
},
132133
renderChunk (code, chunk) {

packages/taro-platform-harmony-cpp/src/program/template/entry.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ export default class Parser extends BaseParser {
337337
` nativeUIManager.initSystemInfo({`,
338338
` deviceInfo: globalThis.loadLibrary('@tarojs/taro', 'getDeviceInfo')(),`,
339339
` })`,
340-
`})();\`, 'npm/${entryFileName}?generated'),`,
340+
`})();\`, '${NPM_DIR}/${entryFileName}?generated'),`,
341341
` ),`,
342342
` new StandardTaroLogger((error: TaroAny) => hilog.error(0xBEEF, "TaroJS ERROR", error.getDetails())),`,
343343
` )).catch((err: Error) => {`,

packages/taro-platform-harmony-cpp/src/program/vite/page-resource.ts

+14-11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from 'node:path'
22

33
import { chalk, fs, NODE_MODULES } from '@tarojs/helper'
44
import { isObject } from '@tarojs/shared'
5+
import fg from 'fast-glob'
56

67
import { genRawFileName, getProjectId, RAWFILE_FOLDER, RAWFILE_NAME_PREFIX } from '../../utils'
78

@@ -48,18 +49,20 @@ export default function (this: Harmony): PluginOption {
4849
}
4950

5051
if (needCleanResources) {
51-
fs.copySync(finalOutDir, tmpDir, {
52-
filter: (src) => {
53-
const copyPath = path.relative(finalOutDir, src)
54-
return (
55-
!copyPath ||
56-
(!copyPath.startsWith('.') &&
57-
!copyPath.startsWith('ets') &&
58-
!copyPath.includes(`${RAWFILE_FOLDER}/${RAWFILE_NAME_PREFIX}`))
59-
)
60-
},
52+
const files = fg.sync(['!cpp/**/*', '!ets/**/*', `!${RAWFILE_FOLDER}/${RAWFILE_NAME_PREFIX}/**/*`], {
53+
cwd: finalOutDir,
54+
dot: true,
55+
})
56+
files.forEach(file => {
57+
const src = path.join(finalOutDir, file)
58+
if (!file.startsWith('ets') && !file.startsWith(`${RAWFILE_FOLDER}/${RAWFILE_NAME_PREFIX}`)) {
59+
const dest = path.join(tmpDir, file)
60+
fs.ensureDirSync(path.dirname(dest))
61+
fs.moveSync(src, dest)
62+
} else {
63+
fs.removeSync(src)
64+
}
6165
})
62-
fs.emptyDirSync(finalOutDir)
6366
;['uncaughtException', 'unhandledRejection', 'uncaughtExceptionMonitor'].forEach((event) => {
6467
process.on(event, (reason) => {
6568
console.error('捕获到未处理的错误:', reason)

0 commit comments

Comments
 (0)