使用Vite构建含React Native模块的React应用时遇Unexpected token错误
解决Vite构建时react-native-toast-message的JSX解析错误
你开发模式下运行正常,但构建时报错,确实是因为.js文件里的JSX没被正确转译。现有配置里的optimizeDeps只在预优化阶段生效,构建阶段的解析逻辑不一样,补以下几个配置就能解决:
1. 让React插件处理JS文件中的JSX
修改@vitejs/plugin-react的配置,明确让它包含.js文件,或者精准匹配react-native-toast-message模块:
plugins: [ react({ // 方案一:匹配所有js/jsx/ts/tsx文件(包括node_modules内的) include: /\.(jsx|tsx|js|ts)$/, // 方案二:仅针对react-native-toast-message,更精准 // include: /node_modules\/react-native-toast-message\/.*\.(js|jsx)$/ }), svgr() ],
2. 配置构建阶段的CommonJS解析
在build选项里添加commonjsOptions,确保该模块被正确识别:
export default defineConfig({ // ...保留你原有的其他配置 build: { commonjsOptions: { include: [/react-native-toast-message/, /node_modules/] } } });
3. 确保构建阶段的esbuild loader生效
调整esbuild配置,让它在构建阶段也能解析JSX:
esbuild: { loader: "tsx", include: /\.(jsx|tsx|js)$/, },
把这些配置加上后,再执行构建应该就能解决这个Unexpected token错误了。
问题详情
开发模式下集成react-native-toast-message等React Native模块的React Web应用运行正常,但执行构建操作时出现如下错误:
[commonjs--resolver] Unexpected token (15:12) in /node_modules/react-native-toast-message/lib/src/Toast.js file: /Library/WebServer/Documents/loyalty-react-admin/node_modules/react-native-toast-message/lib/src/Toast.js:15:12 13: hide 14: }), [hide, show])); 15: return (<ToastUI isVisible={isVisible} options={options} data={data} hide={hide} show={show} config={config}/>);
当前使用的vite.config.ts配置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import svgr from "vite-plugin-svgr"; const extensions = [ ".web.tsx", ".tsx", ".web.ts", ".ts", ".web.jsx", ".jsx", ".web.js", ".js", ".css", ".json", ]; // https://vitejs.dev/config/ export default defineConfig({ esbuild: { loader: "tsx", }, plugins: [ react(), svgr() ], optimizeDeps: { esbuildOptions: { loader: { '.js': 'tsx', }, resolveExtensions: extensions, }, }, resolve: { alias: { 'react-native': 'react-native-web', 'react-native-maps': 'react-native-web-maps', '../Utilities/Platform': 'react-native-web/dist/exports/Platform', '../../Utilities/Platform': 'react-native-web/dist/exports/Platform', './Platform': 'react-native-web/dist/exports/Platform', path: "path-browserify", }, extensions: extensions, }, // define: { // 'process.env': process.env, // }, define: { 'process.env': {} }, server: { host: true, }, base: './', });
内容的提问来源于stack exchange,提问作者Svetlin Stoev
相关产品推荐
相关产品推荐

