Skip to content

Commit

Permalink
wip(uts): 解决部分import报错信息
Browse files Browse the repository at this point in the history
  • Loading branch information
fxy060608 committed Dec 4, 2023
1 parent c6312d0 commit 3826b21
Show file tree
Hide file tree
Showing 10 changed files with 184 additions and 34 deletions.
4 changes: 3 additions & 1 deletion packages/uni-app-plus/dist/uni.x.runtime.esm.js
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,7 @@ function initAnimation(path, animationType, animationDuration) {
];
}

// import { getRouteOptions } from '@dcloudio/uni-core'
// import { $switchTab } from '../../../api/route/switchTab'
let isLaunchWebviewReady = false; // 目前首页双向确定 ready,可能会导致触发两次 onWebviewReady(主要是 Android)
function subscribeWebviewReady(_data, pageId) {
Expand All @@ -1059,7 +1060,7 @@ function onLaunchWebviewReady() {
// plus.navigator.closeSplashscreen()
// }
const entryPagePath = addLeadingSlash(__uniConfig.entryPagePath);
getRouteOptions(entryPagePath);
// const routeOptions = getRouteOptions(entryPagePath)!
const args = {
url: entryPagePath + (__uniConfig.entryPageQuery || ''),
openType: 'appLaunch',
Expand All @@ -1072,6 +1073,7 @@ function onLaunchWebviewReady() {
return $navigateTo(args, handler);
}

// import { getRouteOptions, subscribeServiceMethod } from '@dcloudio/uni-core'
function initSubscribeHandlers() {
// const { subscribe, subscribeHandler, publishHandler } = UniServiceJSBridge
// onPlusMessage<{ type: string; data: Record<string, any>; pageId: number }>(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`imports parseImports 1`] = `"import "./test""`;
19 changes: 19 additions & 0 deletions packages/uni-app-uts/__tests__/android/imports.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { parseImports } from '../../src/plugins/android/utils'

describe('imports', () => {
test(`parseImports`, async () => {
expect(
await parseImports(`
import { test } from './test'
test()
export default {
methods: {
test() {
}
}
}`)
).toMatchSnapshot()
})
})
7 changes: 5 additions & 2 deletions packages/uni-app-uts/src/plugins/android/mainUTS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@dcloudio/uni-cli-shared'

import type { Plugin } from 'vite'
import { parseImports } from './utils'
import { createTryResolve, parseImports } from './utils'

export function uniAppMainPlugin(): Plugin {
const mainUTS = resolveMainPathOnce(process.env.UNI_INPUT_DIR)
Expand All @@ -15,7 +15,10 @@ export function uniAppMainPlugin(): Plugin {
apply: 'build',
async transform(code, id) {
if (normalizePath(id) === mainUTS) {
code = await parseImports(code)
code = await parseImports(
code,
createTryResolve(id, this.resolve.bind(this))
)
return `import './${MANIFEST_JSON_UTS}'
import './${PAGES_JSON_UTS}'
${code}
Expand Down
6 changes: 5 additions & 1 deletion packages/uni-app-uts/src/plugins/android/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
UVUE_CLASS_NAME_PREFIX,
initAutoImportOnce,
getAutoImports,
createTryResolve,
} from './utils'
import { getOutputManifestJson } from './manifestJson'
import { createUniOptions } from '../utils'
Expand Down Expand Up @@ -167,7 +168,10 @@ export function uniAppPlugin(options: {
),
})
}
code = await parseImports(code)
code = await parseImports(
code,
createTryResolve(id, this.resolve.bind(this))
)
return code
},
async writeBundle() {
Expand Down
109 changes: 98 additions & 11 deletions packages/uni-app-uts/src/plugins/android/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import fs from 'fs'
import path from 'path'
import { init, parse } from 'es-module-lexer'
import { ImportSpecifier, init, parse } from 'es-module-lexer'
import {
AutoImportOptions,
createRollupError,
initAutoImportOptions,
normalizeNodeModules,
normalizePath,
offsetToStartAndEnd,
parseUniExtApiNamespacesJsOnce,
removeExt,
} from '@dcloudio/uni-cli-shared'
Expand All @@ -20,17 +21,51 @@ import {

import AutoImport from 'unplugin-auto-import/vite'
import { once } from '@dcloudio/uni-shared'
import { SourceMapInput } from 'rollup'
import type { SourceMapInput, PluginContext } from 'rollup'
import { Position, SourceLocation } from '@vue/compiler-core'

import { createCompilerError } from './uvue/compiler/errors'
import { SourceLocation } from '@vue/compiler-core'

export const UVUE_CLASS_NAME_PREFIX = 'Gen'

export const DEFAULT_APPID = 'HBuilder'

export const ENTRY_FILENAME = 'main.uts'

export async function parseImports(code: string) {
export function createTryResolve(
importer: string,
resolve: PluginContext['resolve'],
offsetLine = 0,
origCode: string = ''
) {
return async (source: string, code: string, { ss, se }: ImportSpecifier) => {
const resolved = await resolve(source, importer)
if (!resolved) {
const { start, end } = offsetToStartAndEnd(code, ss, se)
if (offsetLine) {
start.line = start.line + offsetLine
end.line = end.line + offsetLine
}
if (path.isAbsolute(importer)) {
importer = normalizePath(
path.relative(process.env.UNI_INPUT_DIR, importer)
)
}
throw createResolveError(
(origCode || code).replace(/\r\n/g, '\n'),
`Could not resolve "${source}" from "${importer}"`,
start,
end
)
}
}
}

export async function parseImports(
code: string,
tryResolve?: ReturnType<typeof createTryResolve>
) {
code = code.replace(/\r\n/g, '\n')
await init
let res: ReturnType<typeof parse> = [[], [], false]
try {
Expand All @@ -52,7 +87,7 @@ export async function parseImports(code: string) {
column: parseInt(matches[2]),
},
} as SourceLocation,
{ 0: 'Parse error' },
{ 0: `Parse error` },
''
),
code
Expand All @@ -61,15 +96,67 @@ export async function parseImports(code: string) {
}
throw err
}
return res[0]
.map(({ s, e }) => {
return `import "${code.slice(s, e)}"`
})
.concat(parseUniExtApiImports(code))
.join('\n')
const imports = res[0]
if (!imports.length) {
return ''
}
const importsCode: string[] = []
for (const specifier of res[0]) {
const source = code.slice(specifier.s, specifier.e)
if (tryResolve) {
await tryResolve(source, code, specifier)
}
importsCode.push(`import "${source}"`)
}
return importsCode.concat(parseUniExtApiImports(code)).join('\n')
}

function createResolveError(
code: string,
msg: string,
start: Position,
end: Position
) {
return createRollupError(
'',
'',
createCompilerError(
0,
{
start,
end,
} as SourceLocation,
{ 0: msg },
''
),
code
)
}

// @ts-expect-error 暂时不用
function genImportsCode(code: string, imports: readonly ImportSpecifier[]) {
const chars = code.split('')
const keepChars: number[] = []
imports.forEach(({ ss, se }) => {
for (let i = ss; i <= se; i++) {
keepChars.push(i)
}
})
for (let i = 0; i < chars.length; i++) {
if (!keepChars.includes(i)) {
const char = chars[i]
if (char !== '\r' && char !== '\n') {
chars[i] = ' '
}
}
}
return chars.join('')
}

function parseUniExtApiImports(code: string): string[] {
if (!process.env.UNI_UTS_PLATFORM) {
return []
}
const extApis = parseUniExtApiNamespacesJsOnce(
process.env.UNI_UTS_PLATFORM,
process.env.UNI_UTS_TARGET_LANGUAGE
Expand Down
15 changes: 14 additions & 1 deletion packages/uni-app-uts/src/plugins/android/uvue/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
import {
addAutoImports,
addExtApiComponents,
createTryResolve,
genClassName,
initAutoImportOnce,
isVue,
Expand Down Expand Up @@ -341,7 +342,19 @@ export async function transformVue(
]
const content = descriptor.script?.content
if (content) {
jsCodes.push(await parseImports(content))
jsCodes.push(
await parseImports(
content,
pluginContext
? createTryResolve(
filename,
pluginContext.resolve.bind(pluginContext),
(descriptor.script?.loc.start.line ?? 1) - 1,
descriptor.source
)
: undefined
)
)
}
if (descriptor.styles.length) {
jsCodes.push(await genJsStylesCode(descriptor, pluginContext!))
Expand Down
6 changes: 5 additions & 1 deletion packages/uni-cli-shared/src/vite/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ export {
commonjsProxyRE,
} from './vitejs/plugins/css'

export { generateCodeFrame, locToStartAndEnd } from './vitejs/utils'
export {
generateCodeFrame,
locToStartAndEnd,
offsetToStartAndEnd,
} from './vitejs/utils'
41 changes: 28 additions & 13 deletions packages/uni-cli-shared/src/vite/plugins/vitejs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import os from 'os'
import path from 'path'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
import { SourceLocation } from '@vue/compiler-core'

export function slash(p: string): string {
return p.replace(/\\/g, '/')
Expand Down Expand Up @@ -63,24 +64,38 @@ export function pad(source: string, n = 2): string {
return lines.map((l) => ` `.repeat(n) + l).join(`\n`)
}

export function offsetToLineColumn(
export function offsetToStartAndEnd(
source: string,
offset: number
): { line: number; column: number } {
startOffset: number,
endOffset: number
): SourceLocation {
const lines = source.split(splitRE)
let line = 1
let column = 0
return {
start: offsetToLineColumnByLines(lines, startOffset),
end: offsetToLineColumnByLines(lines, endOffset),
source: '',
}
}

function offsetToLineColumnByLines(lines: string[], offset: number) {
let currentOffset = 0
for (let i = 0; i < lines.length; i++) {
const lineLength = lines[i].length + 1
if (offset <= lineLength) {
column = offset
break
} else {
offset -= lineLength
line++
const lineLength = lines[i].length + 1 // Adding 1 for the newline character
if (currentOffset + lineLength > offset) {
const line = i + 1 // Line numbers start from 1
const column = offset - currentOffset // Column numbers start from 0
return { line, column, offset }
}
currentOffset += lineLength
}
return { line, column }
return { line: lines.length, column: lines[lines.length - 1].length, offset }
}

export function offsetToLineColumn(
source: string,
offset: number
): { line: number; column: number } {
return offsetToLineColumnByLines(source.split(splitRE), offset)
}

export function posToNumber(
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3826b21

Please sign in to comment.