导入@highcharts/highcharts-react-native出现模块解析失败:Unexpected token问题
Module parse failed: Unexpected token 报错解决方案
根因
报错是因为@highcharts/highcharts-react-native包源码使用了未编译的类属性箭头函数语法,React Native Web的Webpack默认配置不会转译node_modules下的第三方包代码,导致解析失败。
可选解决方案
方案一:兼容现有依赖(适合需要同时支持原生端+web端的场景)
- 安装必要的转译插件
npm install --save-dev @babel/plugin-proposal-class-properties @babel/plugin-transform-arrow-functions
- 修改
babel.config.js配置,添加转译插件:
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ ["@babel/plugin-proposal-class-properties", { "loose": true }], "@babel/plugin-transform-arrow-functions" ] };
- 修改Webpack配置,添加对该包的转译规则:
- 普通React Native Web项目:找到Webpack配置文件中babel-loader的配置项,添加该包到转译列表
include: [ path.resolve(__dirname, 'src'), // 新增该行 path.resolve(__dirname, 'node_modules/@highcharts/highcharts-react-native') ]- Expo项目:根目录新建
webpack.config.js写入以下内容
const createExpoWebpackConfigAsync = require('@expo/webpack-config'); const path = require('path'); module.exports = async function (env, argv) { const config = await createExpoWebpackConfigAsync(env, argv); config.module.rules.forEach(rule => { if (rule.oneOf) { rule.oneOf.forEach(item => { if (item.loader && item.loader.includes('babel-loader')) { item.include.push( path.resolve(__dirname, 'node_modules/@highcharts/highcharts-react-native') ); } }) } }) return config; }; - 重启项目,执行
npm run web即可正常运行。
方案二:替换web端依赖(适合仅在web端运行的场景)
highcharts-react-native本身优先适配原生iOS/Android端,web端直接使用官方web适配包可以避免大量兼容问题,且API完全一致:
- 卸载原有依赖
npm uninstall @highcharts/highcharts-react-native
- 安装web端适配包
npm install highcharts highcharts-react-official
- 替换App.js中的组件引用即可,原有图表配置不需要修改。
内容的提问来源于stack exchange,提问作者humberto
相关产品推荐
相关产品推荐

