From 9dacdc46575ba3f8fadbf345bf0919c8e2e0d8e3 Mon Sep 17 00:00:00 2001 From: konka <1094918@gmail.com> Date: Wed, 26 Jul 2023 21:24:04 +0800 Subject: [PATCH] fix: react alias bug on windows --- .../taro-plugin-react/src/webpack.mini.ts | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/taro-plugin-react/src/webpack.mini.ts b/packages/taro-plugin-react/src/webpack.mini.ts index 3b3ae6f614b1..595acf361818 100644 --- a/packages/taro-plugin-react/src/webpack.mini.ts +++ b/packages/taro-plugin-react/src/webpack.mini.ts @@ -1,5 +1,5 @@ - import { fs } from '@tarojs/helper' +import path from 'path' import { getLoaderMeta } from './loader-meta' @@ -22,8 +22,11 @@ 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。 @@ -31,10 +34,10 @@ function setAlias (ctx: IPluginContext, framework: Frameworks, chain) { 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 }) } @@ -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 + }) }