Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: react alias bug on windows #14234

Merged
merged 2 commits into from
Jul 27, 2023
Merged
Changes from all 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
22 changes: 12 additions & 10 deletions packages/taro-plugin-react/src/webpack.mini.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import { fs } from '@tarojs/helper'
import path from 'path'

import { getLoaderMeta } from './loader-meta'

Expand All @@ -22,19 +22,22 @@ function setAlias (ctx: IPluginContext, framework: Frameworks, chain) {
if (!isProd && config.mini?.debugReact !== true) {
// 不是生产环境,且没有设置 debugReact,则使用压缩版本的 react 依赖,减少体积
// 兼容pnpm workspace
const reactModulePath = require.resolve('react', { paths: [process.cwd()] })
const newFilePath = path.join(path.dirname(reactModulePath), 'cjs', 'react.production.min.js')

alias.set('react-reconciler$', 'react-reconciler/cjs/react-reconciler.production.min.js')
alias.set('react$', require.resolve('react', { paths: [process.cwd()] }).replace(/[^/]*$/, 'cjs/react.production.min.js'))
alias.set('react$', newFilePath)
alias.set('react/jsx-runtime$', 'react/cjs/react-jsx-runtime.production.min.js')

// 在React18中,使用了exports字段约定了模块暴露路径,其中并未暴露 ./cjs/ 。这将使上面的alias在编译时报错。相当的tricky。
// Why writeJson? prebundle will load package.json via readFile to check exports property.
const reactPkgPath = require.resolve('react/package.json', { paths: [process.cwd()] })
if (reactPkgPath) {
const reactPkg = require('react/package.json')
const reactVersion = (reactPkg.version || '')
if ((/^[~^]?18/).test(reactVersion) && reactPkg.exports) {
const reactVersion = reactPkg.version || ''
if (/^[~^]?18/.test(reactVersion) && reactPkg.exports) {
reactPkg.exports = Object.assign(reactPkg.exports, {
'./cjs/': './cjs/'
'./cjs/': './cjs/',
})
fs.writeJsonSync(reactPkgPath, reactPkg, { spaces: 2 })
}
Expand All @@ -44,9 +47,8 @@ function setAlias (ctx: IPluginContext, framework: Frameworks, chain) {
}

function setLoader (framework: Frameworks, chain) {
chain.plugin('miniPlugin')
.tap(args => {
args[0].loaderMeta = getLoaderMeta(framework)
return args
})
chain.plugin('miniPlugin').tap((args) => {
args[0].loaderMeta = getLoaderMeta(framework)
return args
})
}