skip to Main Content

I have a react app that uses react-app-rewired, which considers Axios as a string with .cjs format.

this is my config-override.js

const fs = require('fs')
const path = require('path')
const webpack = require('webpack')

const appDirectory = fs.realpathSync(process.cwd())
const resolveApp = relativePath => path.resolve(appDirectory, relativePath)

const appIncludes = [
  resolveApp('src'),
  resolveApp('../components/src'),
]

module.exports = function override(config, env) {
  config.resolve.plugins = config.resolve.plugins.filter(
    plugin => plugin.constructor.name !== 'ModuleScopePlugin'
  )
  config.module.rules[0].include = appIncludes
  config.module.rules[1].oneOf[1].include = appIncludes
  config.module.rules[1].oneOf[3].options.plugins = [
    require.resolve('babel-plugin-react-native-web'),
  ].concat(config.module.rules[1].oneOf[3].options.plugins)

  config.module.rules.push({
    test: /.(js|mjs|cjs)$/,
    exclude: /(@babel(?:/|\{1,2})runtime|node_modules[/\](?!react-native.))/,
    use: {
      loader: "babel-loader",
      options: {
        babelrc: false,
        configFile: false,
        presets: [
          "@babel/preset-react",
          "@babel/preset-flow",
          "@babel/preset-typescript",
          "module:metro-react-native-babel-preset"
        ],
        plugins: [
          "@babel/plugin-proposal-class-properties",
          "@babel/plugin-proposal-object-rest-spread"
        ]
      }
    }
  })

  config.module.rules = config.module.rules.filter(Boolean)
  config.plugins.push(
    new webpack.DefinePlugin({ __DEV__: env !== 'production' })
  )

  return config
}

and I already tried this https://github.com/facebook/create-react-app/issues/11889#issuecomment-1114928008 and https://github.com/facebook/create-react-app/issues/12700#issuecomment-1293290243

how should I fix this problem?

2

Answers


  1. Chosen as BEST ANSWER

    I changed import from import axios from 'axios' to import axios from '../node_modules/axios'


  2. first of all, make sure you have axios installed in your packages :

    npm install axios
    # or
    yarn add axios
    

    then your webpack config should look something like that for override:

     // Add the following alias to your Webpack config to handle Axios imports correctly.
      config.resolve.alias = {
        ...config.resolve.alias,
        axios: path.resolve('./node_modules/axios'),
      };
    

    then restart your server and test it again!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search