Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 193 additions & 0 deletions packages/taro-cli/src/__tests__/create-page.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import * as os from 'node:os'
import * as path from 'node:path'

import { babelKit, fs } from '@tarojs/helper'

import Page, { ConfigModificationState } from '../create/page'
import { modifyPagesOrSubPackages } from '../util/createPage'

// Config updates do not use the native template generator.
jest.mock('@tarojs/binding', () => ({
CompilerType: { Webpack5: 'webpack5' },
CSSType: { None: 'none' },
FrameworkType: { React: 'react' }
}))

function updateConfig (source: string, subPkgRootPath?: string) {
const ast = babelKit.parse(source, { sourceType: 'module' })!
const originalCode = babelKit.generate(ast, { compact: true }).code
const callback = jest.fn()
babelKit.traverse(ast, {
ExportDefaultDeclaration (path) {
modifyPagesOrSubPackages({
path,
fullPagePath: subPkgRootPath ? `${subPkgRootPath}/new/index` : 'pages/new/index',
subPkgRootPath,
callback
})
}
})
expect(callback).toHaveBeenCalledTimes(1)
return {
state: callback.mock.calls[0][0],
code: babelKit.generate(ast, { compact: true }).code,
originalCode
}
}

describe.each(['object', 'defineAppConfig'])('create page config: %s', (format) => {
const wrap = (config: string) => `export default ${format === 'object' ? config : `defineAppConfig(${config})`}`

it.each([
'pages: ["pages/home/index"]',
'"pages": ["pages/home/index"]',
'...baseConfig, pages: ["pages/home/index"]',
'...baseConfig, "pages": ["pages/home/index"]',
'get pages() { return [] }, "pages": ["pages/home/index"]',
'[pages]: [], "pages": ["pages/home/index"]'
])('appends to explicit pages: %s', (properties) => {
const result = updateConfig(wrap(`{ ${properties} }`))
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain('["pages/home/index","pages/new/index"]')
if (properties.includes('...baseConfig')) expect(result.code).toContain('...baseConfig')
if (properties.includes('[pages]')) expect(result.code).toContain('[pages]:[]')
})

it.each(['pages', '"pages"'])('does not duplicate an existing page: %s', (key) => {
const result = updateConfig(wrap(`{ ${key}: ["pages/new/index"] }`))
expect(result.state).toBe(ConfigModificationState.NeedLess)
expect(result.code).toBe(result.originalCode)
})

it.each([
['"pages"', 'pages'],
['pages', '"pages"'],
['pages', 'pages'],
['"pages"', '"pages"']
])('updates the last pages property: %s followed by %s', (firstKey, lastKey) => {
const result = updateConfig(wrap(`{ ${firstKey}: ["ignored"], ${lastKey}: ["pages/home/index"] }`))
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain(`${firstKey}:["ignored"]`)
expect(result.code).toContain(`${lastKey}:["pages/home/index","pages/new/index"]`)
})

it('checks duplicates in the last pages property', () => {
const result = updateConfig(wrap('{ "pages": [], pages: ["pages/new/index"] }'))
expect(result.state).toBe(ConfigModificationState.NeedLess)
expect(result.code).toBe(result.originalCode)
})

it('leaves a nonliteral last pages property unchanged', () => {
const result = updateConfig(wrap('{ "pages": [], pages: pageList }'))
expect(result.state).toBe(ConfigModificationState.Fail)
expect(result.code).toBe(result.originalCode)
})

it.each([
'{}',
'{ ...baseConfig }',
'{ pages: pageList }',
'{ [pages]: [] }',
'{ ["pages"]: [] }',
'{ pages() { return [] } }'
])('leaves unsupported pages config unchanged: %s', (config) => {
const result = updateConfig(wrap(config))
expect(result.state).toBe(ConfigModificationState.Fail)
expect(result.code).toBe(result.originalCode)
})

it.each([
'subPackages: [{ root: "pkg/", pages: ["home/index"] }]',
'"subPackages": [{ "root": "pkg/", "pages": ["home/index"] }]',
'...baseConfig, "subPackages": [{ ...subConfig, "root": "pkg/", "pages": ["home/index"] }]',
'subPackages: [{ root() {}, root: "pkg/", pages() {}, pages: ["home/index"] }]'
])('updates an existing subpackage: %s', (properties) => {
const result = updateConfig(wrap(`{ ${properties} }`), 'pkg')
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain('["home/index","new/index"]')
expect(result.code.match(/"pkg\/"/g)).toHaveLength(1)
})

it('does not duplicate a page in a quoted subpackage config', () => {
const result = updateConfig(wrap('{ "subPackages": [{ "root": "pkg/", "pages": ["new/index"] }] }'), 'pkg')
expect(result.state).toBe(ConfigModificationState.NeedLess)
expect(result.code).toBe(result.originalCode)
})

it.each([
'{ "subPackages": [{ root: "ignored/", pages: [] }], subPackages: [{ root: "pkg/", pages: ["home/index"] }] }',
'{ subPackages: [{ "root": "ignored/", root: "pkg/", pages: ["home/index"] }] }',
'{ subPackages: [{ root: "pkg/", "pages": ["ignored"], pages: ["home/index"] }] }'
])('updates the effective subpackage properties: %s', (config) => {
const result = updateConfig(wrap(config), 'pkg')
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain('pages:["home/index","new/index"]')
expect(result.code).toContain('"ignored')
expect(result.code.match(/"pkg\/"/g)).toHaveLength(1)
})

it('matches the root property instead of an unrelated string value', () => {
const result = updateConfig(wrap('{ subPackages: [{ name: "pkg/", root: "other/", pages: [] }, { "root": "pkg/", "pages": ["home/index"] }] }'), 'pkg')
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain('root:"other/",pages:[]')
expect(result.code).toContain('"root":"pkg/","pages":["home/index","new/index"]')
})

it('adds a missing subPackages property after a spread', () => {
const result = updateConfig(wrap('{ ...baseConfig, pages: [] }'), 'pkg')
expect(result.state).toBe(ConfigModificationState.Success)
expect(result.code).toContain('...baseConfig')
expect(result.code).toContain('subPackages:[{root:"pkg/",pages:["new/index"]}]')
})

it.each([
'{ "subPackages": subPackages }',
'{ "subPackages": [{ "root": "pkg/", "pages": pageList }] }'
])('leaves nonliteral subpackage configs unchanged: %s', (config) => {
const result = updateConfig(wrap(config), 'pkg')
expect(result.state).toBe(ConfigModificationState.Fail)
expect(result.code).toBe(result.originalCode)
})
})

it.each(['defineAppConfig()', 'defineAppConfig(config)', 'defineAppConfig(null)'])(
'leaves a non-object config unchanged: %s', (config) => {
for (const subPkgRootPath of [undefined, 'pkg']) {
const result = updateConfig(`export default ${config}`, subPkgRootPath)
expect(result.state).toBe(ConfigModificationState.Fail)
expect(result.code).toBe(result.originalCode)
}
}
)

describe('create page config file updates', () => {
let projectDir: string

beforeEach(() => {
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'taro-create-page-'))
jest.spyOn(console, 'log').mockImplementation(() => {})
})

afterEach(() => {
fs.removeSync(projectDir)
jest.restoreAllMocks()
})

it.each(['js', 'ts'])('writes the new page to app.config.%s', (extension) => {
const configPath = path.join(projectDir, 'src', `app.config.${extension}`)
const baseConfig = extension === 'ts' ? 'const baseConfig: { window?: object } = {}' : 'const baseConfig = {}'
fs.outputFileSync(configPath, `${baseConfig}\nexport default defineAppConfig({ ...baseConfig, "pages": ["pages/home/index"] })`)
const page = Object.create(Page.prototype)
page.conf = { projectDir, typescript: extension === 'ts' }
page.pageEntryPath = '/src/pages/new/index'

page.updateAppConfig()
const updated = fs.readFileSync(configPath, 'utf8')
expect(updated).toContain('pages/home/index')
expect(updated).toContain('pages/new/index')
expect(updated).toContain('...baseConfig')

page.updateAppConfig()
expect(fs.readFileSync(configPath, 'utf8')).toBe(updated)
})
})
31 changes: 22 additions & 9 deletions packages/taro-cli/src/util/createPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,22 @@ import { babelKit } from '@tarojs/helper'

import { ConfigModificationState, ModifyCallback } from '../create/page'

import type { ArrayExpression, ExportDefaultDeclaration, ObjectExpression, ObjectProperty } from '@babel/types'
import type { ArrayExpression, ExportDefaultDeclaration, Node, ObjectExpression, ObjectProperty } from '@babel/types'
import type { NodePath } from 'babel__traverse'

const t = babelKit.types

const getObjectProperty = (node: Node | null | undefined, name: string): ObjectProperty | undefined => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的参数类型是 Node | null | undefined,但当前 Babel types 的类型守卫不会把 node 收窄到 ObjectExpression,因此访问 node.properties 会导致 TypeScript 编译失败(TS18049/TS2339)。

建议将参数类型限制为 ObjectExpression | null | undefined,或先通过显式类型守卫得到一个 ObjectExpression 局部变量后再访问 properties。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感谢指出,已在 0d65b9c 中改为直接检查 node?.type !== 'ObjectExpression',通过 AST 的 type 字段显式收窄类型,再访问 properties,避免依赖这里的 Babel 类型守卫。

修改后 CLI 的 tsc 构建、ESLint 和 69 个页面配置测试均通过。本机原代码也能通过构建,暂未复现您报告的编译错误,因此补上了明确的类型检查,烦请复查。

另外如实补充全量测试结果:226 个通过、7 个跳过、2 个失败。两项失败均位于 doctor-config.spec.ts,预期的 framework 选项包含 none,但本机安装的 @tarojs/plugin-doctor 返回的选项不包含它;已通过直接调用该插件确认这一差异。

if (node?.type !== 'ObjectExpression') return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Later explicit properties override earlier properties with the same key.
for (let index = node.properties.length - 1; index >= 0; index--) {
const property = node.properties[index]
if (t.isObjectProperty(property) && !property.computed && (
t.isIdentifier(property.key, { name }) || t.isStringLiteral(property.key, { value: name })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里只匹配 ObjectProperty,跳过了同名的 ObjectMethod/getter/setter。

例如:

export default {
pages: [],
pages() {}
}

或者:

export default {
pages: [],
get pages() {
return []
}
}

Babel 会将这些 method/getter 解析为 ObjectMethod。运行时真正生效的是后面的成员,但当前实现会跳过它,转而修改前面的 pages 数组,并返回 Success,导致新页面实际上不会注册。

旧实现会命中同名 method,并因为其值不是数组而返回 Fail,因此这里会把原本安全失败的情况变成静默修改无效配置的回归。subPackages 中的 root 和 pages 也存在同样问题。

建议从右向左扫描所有同名且非 computed 的成员:如果最后生效的成员是 ObjectProperty,再校验其值;如果是 ObjectMethod/getter/setter,则直接视为不支持并返回 Fail,不要回退到更早的属性。同时补充上述场景的回归测试。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感谢指出,确实存在跳过后置 ObjectMethod 后修改无效属性并返回 Success 的回归。已在 00a7f4d 中修复:

  • 从右向左扫描成员;最后生效的同名成员如果是 method/getter/setter,就视为不支持,不再回退到更早的数组属性。
  • 同时处理后置展开和计算属性可能覆盖目标字段的情况,无法静态确定时返回 Fail。
  • 区分“属性确实不存在”和“属性无法安全解析”,避免把不支持的 subPackages/root 当成缺失而新增配置。后置显式数组覆盖前置成员的情况仍可正常更新。

补充了普通对象与 defineAppConfig 两种形式的主包 pages、subPackages、分包 root/pages 回归测试,以及后置显式属性正常覆盖的用例。修复前该测试集 42 个失败、79 个通过;修复后 121 个全部通过。CLI 的 tsc 构建、修改文件 ESLint 和 git diff --check 均通过。本轮未重跑 CLI 全量测试;此前 doctor 插件选项与测试预期不一致的两项失败已在前面的回复中说明。

烦请复查。

)) return property
}
}

const generateNewSubPackageItem = (subPackage: string) => {
const pageObject = t.objectProperty(t.identifier('pages'), t.arrayExpression([]))
const subPkgRootObject = t.objectProperty(t.identifier('root'), t.stringLiteral(subPackage))
Expand All @@ -15,16 +26,16 @@ const generateNewSubPackageItem = (subPackage: string) => {
}

const isValidSubPkgObject = (subPkgObject: ObjectExpression) => {
const properties = subPkgObject?.properties || {}
const rootProperty = properties.find((property: ObjectProperty) => (property.key as any)?.name === 'root') as ObjectProperty
const pagesProperty = properties.find((property: ObjectProperty) => (property.key as any)?.name === 'pages') as ObjectProperty
const rootProperty = getObjectProperty(subPkgObject, 'root')
const pagesProperty = getObjectProperty(subPkgObject, 'pages')
const rootPropertyValueType = rootProperty?.value?.type
const pagesPropertyValueType = pagesProperty?.value?.type
return rootPropertyValueType === 'StringLiteral' && pagesPropertyValueType === 'ArrayExpression'
}

const addNewSubPackage = (node: ObjectExpression, page: string, subPackage: string): ConfigModificationState => {
let subPackages = node?.properties.find(node => (node as any).key.name === 'subPackages') as ObjectProperty
if (!t.isObjectExpression(node)) return ConfigModificationState.Fail
let subPackages = getObjectProperty(node, 'subPackages')
if (!subPackages) {
// config 文件不存在 subPackages 字段的情况,给该字段赋予默认值
const subPkgObject = t.objectProperty(t.identifier('subPackages'), t.arrayExpression([]))
Expand All @@ -35,7 +46,9 @@ const addNewSubPackage = (node: ObjectExpression, page: string, subPackage: stri

// 文件格式不对的情况
if (!value || value?.type !== 'ArrayExpression') return ConfigModificationState.Fail
let targetSubPkgObject: ObjectExpression = value.elements.find(node => (node as any)?.properties?.find(property => (property as any)?.value?.value === subPackage)) as ObjectExpression
let targetSubPkgObject = value.elements.find(node =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

targetSubPkgObject 的类型仍然是 ObjectExpression | undefined。当前分支赋值后,TypeScript 仍会在第 60 行和 isValidSubPkgObject(targetSubPkgObject) 处报告 TS18048/TS2345。

建议在分支后显式建立非空的 ObjectExpression 变量,或增加明确的类型守卫,确保 CLI 能通过 tsc 构建。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 0d65b9c 中补上明确的非空检查:先排除 !targetSubPkgObject,再访问 .type 并调用 isValidSubPkgObject,使后续使用的对象类型明确为非空的 ObjectExpression。

修改后 CLI 的 tsc 构建和 69 个页面配置测试通过,感谢 review,烦请复查。

t.isStringLiteral(getObjectProperty(node, 'root')?.value, { value: subPackage })
) as ObjectExpression | undefined

if (!targetSubPkgObject) {
// 不存在 当前分包配置对象的情况
Expand All @@ -44,8 +57,8 @@ const addNewSubPackage = (node: ObjectExpression, page: string, subPackage: stri
value.elements.push(subPkgItemObject)
}

if (targetSubPkgObject.type !== 'ObjectExpression' || !isValidSubPkgObject(targetSubPkgObject)) return ConfigModificationState.Fail
const pagesProperty: ObjectProperty = targetSubPkgObject.properties.find((property: ObjectProperty) => (property.key as any)?.name === 'pages') as ObjectProperty
if (!targetSubPkgObject || targetSubPkgObject.type !== 'ObjectExpression' || !isValidSubPkgObject(targetSubPkgObject)) return ConfigModificationState.Fail
const pagesProperty = getObjectProperty(targetSubPkgObject, 'pages')!
const currentPages = (pagesProperty.value as ArrayExpression).elements
const isPageExists = Boolean(currentPages.find(node => (node as any).value === page))

Expand All @@ -56,7 +69,7 @@ const addNewSubPackage = (node: ObjectExpression, page: string, subPackage: stri
}

const addNewPage = (node: ObjectExpression, page: string): ConfigModificationState => {
const pages = node?.properties.find(node => (node as any).key.name === 'pages') as ObjectProperty
const pages = getObjectProperty(node, 'pages')
if (!pages) return ConfigModificationState.Fail

const value = pages?.value
Expand Down
Loading