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

React集成aws-amplify时出现"require is not defined"错误

Fixing the require is not defined Error After Adding aws-amplify to Your React Project

Hey there, that error pops up because webpack isn't properly converting the CommonJS require syntax used inside aws-amplify into code that browsers can understand. Let's walk through the fixes step by step, based on your webpack config:

1. Fix Your babel-loader Configuration

Right now, your babel-loader is missing key settings to properly transpile React and ES6 code (plus handle modules from aws-amplify). First, install the necessary Babel dependencies if you haven't already:

npm install @babel/core @babel/preset-react @babel/preset-env babel-loader --save-dev

Then update the module.rules section in your webpack.config.js:

module: {
  rules: [{
    test: /\.(js|jsx)$/, // Tell babel-loader to process .js and .jsx files
    include: DEV,
    exclude: /node_modules/, // Skip node_modules unless you still have issues (then remove this line)
    loader: "babel-loader",
    options: {
      presets: ["@babel/preset-react", "@babel/preset-env"] // Transpile React and modern JS
    }
  }]
}

2. Add Resolve Extensions and Fallbacks

Webpack needs clear guidance on which file extensions to resolve, and some aws-amplify dependencies might rely on Node.js modules that aren't available in browsers. Add this resolve block to your config:

resolve: {
  extensions: ['.js', '.jsx', '.json'], // Let webpack auto-detect these file types
  fallback: {
    // Disable Node-specific modules we don't need in the browser
    "fs": false,
    "path": false,
    // If aws-amplify needs crypto, install the browser polyfill first
    "crypto": require.resolve("crypto-browserify")
  }
}

If you need the crypto polyfill, install it first:

npm install crypto-browserify --save-dev

3. Ensure Target is Set to Browser

Double-check that webpack is building for the browser environment (this is default, but it never hurts to confirm):

target: 'web',

4. Verify Your Amplify Import and Setup

Make sure you're importing and configuring Amplify correctly in your React code:

import Amplify from 'aws-amplify';
// If you used the Amplify CLI, import your generated config file
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

Finally, Rebuild and Test

Run your webpack build again and refresh the page:

npx webpack --mode development

That should resolve the require is not defined error and get your React app working with aws-amplify again!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:58:26