You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Storybook中at-loader无法解析react-native的AccessibilityInfo模块求助

解决Storybook无法解析React Native模块及at-loader错误的方案

你的问题核心在于Storybook运行在Web环境,但React Native的部分模块(比如AccessibilityInfo)只有原生端实现,Webpack找不到对应文件,同时TypeScript的类型解析也没适配Web环境。下面是一步步的解决办法:

1. 调整Webpack配置,处理RN模块映射

修改.storybook/webpack.config.js,添加别名映射缺失模块,并适配babel编译规则:

const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js');
const path = require('path');

module.exports = (baseConfig, env) => {
  const config = genDefaultConfig(baseConfig, env);

  // 配置TypeScript loader,指定tsconfig路径
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    loader: require.resolve('awesome-typescript-loader'),
    options: {
      configFileName: path.resolve(__dirname, '../tsconfig.json')
    }
  });
  config.resolve.extensions.push('.ts', '.tsx');

  // 关键:映射RN模块到Web兼容实现,mock缺失的原生模块
  config.resolve.alias = {
    ...config.resolve.alias,
    'react-native$': 'react-native-web',
    'AccessibilityInfo': path.resolve(__dirname, '../__mocks__/AccessibilityInfo.js')
  };

  // 让babel-loader处理react-native目录下的文件,避免语法错误
  config.module.rules.forEach(rule => {
    if (rule.test.toString().includes('js|jsx')) {
      rule.include.push(path.resolve(__dirname, '../node_modules/react-native'));
    }
  });

  return config;
};

2. 创建缺失模块的Mock文件

在项目根目录新建__mocks__/AccessibilityInfo.js,模拟模块基础功能以满足Web环境导入需求:

// Mock AccessibilityInfo模块,提供空实现
const AccessibilityInfo = {
  addEventListener: () => {},
  removeEventListener: () => {},
  announceForAccessibility: () => {},
  isScreenReaderEnabled: async () => false,
};

export default AccessibilityInfo;

3. 适配TypeScript配置,修复类型解析

修改tsconfig.json,添加Web环境的RN类型支持:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es6",
    "module": "commonjs",
    "lib": ["es2017", "dom"],
    "jsx": "react",
    "sourceMap": true,
    "outDir": "./lib",

    /* Strict Type-Checking Options */
    "strict": true,
    "strictNullChecks": true,
    "noImplicitThis": false,

    /* Module Resolution Options */
    "baseUrl": ".",
    "paths": { 
      "*": ["*", "*.ios", "*.android"],
      "react-native": ["node_modules/react-native-web"]
    },
    "types": ["react-native", "react-native-web"]
  },
  "include": ["./src/**/*", "./__mocks__/**/*"],
  "exclude": ["./node_modules/**/*"]
}

4. 安装必要依赖

安装Web环境兼容的RN实现包及类型声明:

npm install react-native-web --save-dev
npm install @types/react-native-web --save-dev

5. 验证修复

重新运行npm run storybook,此时AccessibilityInfo的模块找不到错误应该会消失,at-loader的185个类型错误也会因为TypeScript能正确解析RN模块类型而得到解决。

额外提示

如果后续遇到其他RN原生模块缺失的问题,都可以用类似的mock方式处理,或者优先使用react-native-web提供的Web替代实现。另外,也可以调整.babelrc为["react-native", { "useBuiltIns": true }],优化React Native代码在Web环境的编译效果。

内容的提问来源于stack exchange,提问作者martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:44:36