Create-react-app: proxy server config error::: Must use import to load ES Module

Created on 19 Nov 2020  路  2Comments  路  Source: facebook/create-react-app

Description

Crashing when running npm start with setupProxy.js
I configured proxy server manually, created setupProxy.js in my src folder. The problem is that I'm using new ES6 modules in node.js and when I'm running npm start I get this error:

Must use import to load ES Module: C:\Users\d\projects\vsrc\setupProxy.js
require() of ES modules is not supported.
require() of C:\Users\d\projects\vsrc\setupProxy.js from C:\Users\d\projects
\v\node_modules\react-scripts\config\webpackDevServer.config.js is an ES module file as it is a .js file
whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as
ES modules.
Instead rename setupProxy.js to end in .cjs, change the requiring code to use import(), or remove "type": "module
" from C:\Users\d\projects\v\package.json.

Proxy config:

import { createRequire } from 'module';

const require = createRequire(import.meta.url);

const proxy = require('http-proxy-middleware');

const target = process.env.PROXY_TARGET;

if (!target) {
throw new Error('Please specify the proxy target in your environment variables.');
}

export default (app) => {
app.use(
'/api/v1',
proxy({
target,
changeOrigin: true,
secure: false,
}),
);
};

Did you try recovering your dependencies?

Yes

Which terms did you search for in User Guide?

  • create-react-app proxy config
  • create-react-app Must use import to load ES Module
  • webpack Must use import to load ES Module

Environment

System:
OS: Windows 10 10.0.17763
CPU: (8) x64 Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz
Binaries:
Node: 14.14.0 - C:\Program Files\nodejs\node.EXE
Yarn: Not Found
npm: 6.14.8 - C:\Program Files\nodejs\npm.CMD
Browsers:
Chrome: 83.0.4103.61
Edge: Spartan (44.17763.831.0)
Internet Explorer: 11.0.17763.771
npmPackages:
react: ~16.13.1 => 16.13.1
react-dom: ~16.13.1 => 16.13.1
react-scripts: 4.0.0 => 4.0.0
npmGlobalPackages:
create-react-app: Not Found

Steps to reproduce

  1. install node.js 14+
  2. set "type": "module" in your package.json
  3. config a proxy server using setupProxy.js file
  4. run npm start

Expected behavior

Should run dev server with proxy

Actual behavior

crashing with error

bug report needs triage

All 2 comments

+1

I created a new project and could successfully reproduced the BUG. You can clone it and try
https://github.com/gegham1/react-scripts-bug

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fson picture fson  路  3Comments

stopachka picture stopachka  路  3Comments

JimmyLv picture JimmyLv  路  3Comments

rdamian3 picture rdamian3  路  3Comments

alleroux picture alleroux  路  3Comments