Skip to content

Commit

Permalink
fix(vite): fix h5 build error when use vite
Browse files Browse the repository at this point in the history
- fix vite build h5 error, mostly due to different separators on window
- fix h5 cannot use Taro.API when use vite
- fix Taro.options.html not mounted when use webpack
  • Loading branch information
TheKonka committed Aug 4, 2024
1 parent 39dd83e commit 7f93d1b
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 41 deletions.
13 changes: 9 additions & 4 deletions packages/taro-platform-h5/src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ export default class H5 extends TaroPlatformWeb {
break
default:
if (this.useHtmlComponents) {
args[0].loaderMeta.extraImportForWeb += `import '${require.resolve('@tarojs/components-react/dist/index.css')}'\nimport { PullDownRefresh } from '@tarojs/components'\n`
args[0].loaderMeta.extraImportForWeb += `import '${require.resolve(
'@tarojs/components-react/dist/index.css'
)}'\nimport { PullDownRefresh } from '@tarojs/components'\n`
args[0].loaderMeta.execBeforeCreateWebApp += `config.PullDownRefresh = PullDownRefresh\n`
}
}
Expand Down Expand Up @@ -180,7 +182,7 @@ export default class H5 extends TaroPlatformWeb {
function injectLoaderMeta() {
return {
name: 'taro:vite-h5-loader-meta',
async buildStart () {
async buildStart() {
const viteCompilerContext = await getViteH5CompilerContext(this)
if (viteCompilerContext) {
viteCompilerContext.loaderMeta ||= {
Expand Down Expand Up @@ -222,7 +224,10 @@ export default class H5 extends TaroPlatformWeb {
const viteCompilerContext = await getViteH5CompilerContext(this)
if (viteCompilerContext) {
const exts = Array.from(new Set(viteCompilerContext.frameworkExts.concat(SCRIPT_EXT)))
if (id.startsWith(viteCompilerContext.sourceDir) && exts.some((ext) => id.includes(ext))) {
if (
path.normalize(id).startsWith(viteCompilerContext.sourceDir) &&
exts.some((ext) => id.includes(ext))
) {
// @TODO 后续考虑使用 SWC 插件的方式实现
const result = await transformAsync(code, {
filename: id,
Expand All @@ -231,7 +236,7 @@ export default class H5 extends TaroPlatformWeb {
require('babel-plugin-transform-taroapi'),
{
packageName: '@tarojs/taro',
definition: require(that.libraryDefinition)
definition: require(that.libraryDefinition),
},
],
],
Expand Down
66 changes: 32 additions & 34 deletions packages/taro-vite-runner/src/h5/mpa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,28 @@ export default function (viteCompilerContext: ViteH5CompilerContext): PluginOpti
designWidth: taroConfig.designWidth,
deviceRatio: taroConfig.deviceRatio,
option: taroConfig.postcss,
esnextModules: taroConfig.esnextModules || []
esnextModules: taroConfig.esnextModules || [],
})

const [, pxtransformOption] = __postcssOption.find(([name]) => name === 'postcss-pxtransform') || []

function createRewire (
reg: string,
baseUrl: string,
proxyUrlKeys: string[],
) {
function createRewire(reg: string, baseUrl: string, proxyUrlKeys: string[]) {
return {
from: new RegExp(`/${reg}.html`),
to({ parsedUrl }) {
const pathname: string = parsedUrl.pathname
const excludeBaseUrl = pathname.replace(baseUrl, '/')
const template = path.resolve(baseUrl, 'index.html')
const template = path.posix.join(baseUrl, 'index.html')
if (excludeBaseUrl === '/') {
return template
}
const isApiUrl = proxyUrlKeys.some((item) =>
pathname.startsWith(path.resolve(baseUrl, item)),
)
const isApiUrl = proxyUrlKeys.some((item) => pathname.startsWith(path.posix.join(baseUrl, item)))
return isApiUrl ? excludeBaseUrl : template
},
}
}

function getIsHtmlEntry (pathName: string) {
function getIsHtmlEntry(pathName: string) {
return pages.some(({ name }) => {
const pageName = removeHeadSlash(path.join(basename, name))
const htmlPath = path.join(appPath, taroConfig.sourceRoot || 'src', `${pageName}.html`)
Expand All @@ -60,7 +54,7 @@ export default function (viteCompilerContext: ViteH5CompilerContext): PluginOpti
const input = {}
pages.forEach((page) => {
const { name } = page
const pageName = removeHeadSlash(path.join(basename, name))
const pageName = removeHeadSlash(path.posix.join(basename, name))
const htmlPath = path.join(appPath, taroConfig.sourceRoot || 'src', `${pageName}.html`)
input[pageName] = htmlPath
})
Expand All @@ -70,69 +64,71 @@ export default function (viteCompilerContext: ViteH5CompilerContext): PluginOpti
return {
name: 'taro:vite-h5-mpa',
enforce: 'pre',
buildStart () {
buildStart() {
const getRoutesConfig = (pageName: string) => {
const page = pages.find(({ name }) => name === pageName) || pages[0] as VitePageMeta
const page = pages.find(({ name }) => name === pageName) || (pages[0] as VitePageMeta)
const routesConfig = [
'config.routes = []',
`config.route = ${genRouterResource(page)}`,
`config.pageName = "${pageName}"`
`config.pageName = "${page.name}"`,
].join('\n')
return routesConfig
}
viteCompilerContext.routerMeta = {
routerCreator: 'createMultiRouter',
getRoutesConfig
getRoutesConfig,
}
},
config: () => ({
build: {
rollupOptions: {
input: getInput(),
output: {
entryFileNames: (chunkInfo) => `js/${chunkInfo.name}.[hash].js`
}
}
}
entryFileNames: (chunkInfo) => `js/${chunkInfo.name}.[hash].js`,
},
},
},
}),
configureServer (server) {
configureServer(server) {
const rewrites: { from: RegExp, to: any }[] = []
const proxy = server.config.server.proxy || {}
const proxyKeys = Object.keys(proxy)
const baseUrl = server.config.base ?? '/'
pages.forEach(({ name }) => {
const pageName = removeHeadSlash(path.join(basename, name))
const pageName = removeHeadSlash(path.posix.join(basename, name))
rewrites.push(createRewire(pageName, baseUrl, proxyKeys))
})
server.middlewares.use(history({
disableDotRule: undefined,
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
rewrites: rewrites
}))
server.middlewares.use(
history({
disableDotRule: undefined,
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
rewrites: rewrites,
})
)
},
async resolveId (source, importer, options) {
async resolveId(source, importer, options) {
// 处理 html 文件
const isEntry = getIsHtmlEntry(source)
if (isEntry) return source

// 处理 config.ts 入口文件
const resolved = await this.resolve(source, importer, { ...options, skipSelf: true })
if (resolved?.id && pages.some(({ configPath }) => resolved.id.startsWith(configPath))) {
if (resolved?.id && pages.some(({ configPath }) => resolved.id.startsWith(configPath.replace(/\\/g, '/')))) {
// mpa 模式,入口文件为每个page下的config
const queryParams = getQueryParams(source)
const pageName = queryParams?.[PAGENAME_QUERY]
const pureId = path.parse(resolved.id).dir
const params = {
[ENTRY_QUERY]: 'true',
[PAGENAME_QUERY]: pageName as string
[PAGENAME_QUERY]: pageName as string,
}
const queryString = generateQueryString(params)
return appendVirtualModulePrefix(pureId + `?${queryString}`)
}

return null
},
load (id) {
load(id) {
// 处理 html 文件
const isEntryHtml = getIsHtmlEntry(id)
if (isEntryHtml) return htmlTemplate
Expand All @@ -145,9 +141,11 @@ export default function (viteCompilerContext: ViteH5CompilerContext): PluginOpti
let srciptSource = configPath.replace(sourceDir, '')
let page
if (isProd) {
page = pages.filter(({ name }) => filePath?.startsWith(`/${removeHeadSlash(path.join(basename, name))}`))?.[0]
page = pages.find(({ name }) => filePath?.startsWith(`/${removeHeadSlash(path.posix.join(basename, name))}`))
} else {
page = pages.filter(({ name }) => originalUrl?.startsWith(`/${removeHeadSlash(path.join(basename, name))}`))?.[0]
page = pages.find(({ name }) =>
originalUrl?.startsWith(`/${removeHeadSlash(path.posix.join(basename, name))}`)
)
}
if (page) {
const params = { [PAGENAME_QUERY]: page.name }
Expand All @@ -157,7 +155,7 @@ export default function (viteCompilerContext: ViteH5CompilerContext): PluginOpti
const htmlScript = getHtmlScript(srciptSource, pxtransformOption)

return html.replace(/<script><%= htmlWebpackPlugin.options.script %><\/script>/, htmlScript)
}
},
},
}
}
4 changes: 2 additions & 2 deletions packages/taro-vite-runner/src/utils/html.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function getHtmlScript (entryScript: string, pxtransformOption): string {
export function getHtmlScript(entryScript: string, pxtransformOption): string {
let htmlScript = ''
const options = pxtransformOption?.config || {}
const max = options?.maxRootSize ?? 40
Expand All @@ -11,6 +11,6 @@ export function getHtmlScript (entryScript: string, pxtransformOption): string {
if ((options?.targetUnit ?? 'rem') === 'rem') {
htmlScript = `<script>!function(n){function f(){var e=n.document.documentElement,r=e.getBoundingClientRect(),width=r.width,height=r.height,arr=[width,height].filter(function(value){return Boolean(value)}),w=Math.min.apply(Math,arr),x=${rootValue}*w/${designWidth};e.style.fontSize=x>=${max}?"${max}px":x<=${min}?"${min}px":x+"px"}; n.addEventListener("resize",(function(){f()})),f()}(window);</script>\n`
}
htmlScript += ` <script type="module" src="${entryScript}"></script>`
htmlScript += ` <script type="module" src="${entryScript.replace(/\\/g, '/')}"></script>`
return htmlScript
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class MiniBaseConfig extends BaseConfig {
// 小程序使用 [email protected]
'regenerator-runtime': require.resolve('regenerator-runtime'),
// 开发组件库时 link 到本地调试,runtime 包需要指向本地 node_modules 顶层的 runtime,保证闭包值 Current 一致,shared 也一样
'@tarojs/runtime': resolveSync('@tarojs/runtime', resolveOptions),
'@tarojs/runtime': resolveSync('@tarojs/runtime', { basedir: appPath, mainFields: ['main', ...mainFields] }),
'@tarojs/shared': resolveSync('@tarojs/shared', resolveOptions),
},
// [Webpack 4] config.node: { fs: false, path: false }
Expand Down

0 comments on commit 7f93d1b

Please sign in to comment.