将http-proxy-middleware与Typescript和cross-env一起使用

问题描述

我正在尝试使用http-proxy-middleware为我的React TypeScript应用程序设置代理,以防止开发时出现CORS错误

我的项目中有这个

proxy / proxy.tsx

import * as express from 'express'
import { createProxyMiddleware } from 'http-proxy-middleware'

const app = express()

app.use('/api',createProxyMiddleware({ target: 'localhost:8080',changeOrigin: true }))
app.listen(3000)

然后进入

package.json

"main": "src/index.tsx","scripts": {
  ...
  "proxy": "cross-env nodemon proxy/proxy",...
},

但是,当我在控制台中运行脚本时,会得到以下提示

[nodemon] starting `node proxy/proxy src/index.tsx`
(node:28564) Warning: To load an ES module,set "type": "module" in the package.json or use the .mjs extension.
C:\*path to project*\pet-project-fe\src\index.tsx:1
import React from 'react'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

如果我尝试将type": "module"添加到packages.json,则我的实际应用会由于以下错误而停止运行:

"C:\Program Files\nodejs\node.exe" C:\*path to npm*\npm\node_modules\yarn\bin\yarn.js run start
yarn run v1.22.4
$ cross-env NODE_ENV=development webpack-dev-server --open --content-base ./public --port 3001
internal/modules/cjs/loader.js:1153
      throw new ERR_REQUIRE_ESM(filename,parentPath,packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\*path to project*\pet-project-fe\webpack.config.js
require() of ES modules is not supported.
require() of C:\*path to project*\pet-project-fe\webpack.config.js from C:\*path to project*\pet-project-fe\node_modules\webpack-cli
\bin\utils\convert-argv.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 webpack.config.js to end in .cjs,change the requiring code to use import(),or remove "type": "module" from C:\*path to project*\pet-project-fe\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:13)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at WEBPACK_OPTIONS (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:114:13)
    at requireConfig (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:116:6)
    at C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:123:17
    at Array.forEach (<anonymous>)
    at module.exports (C:\*path to project*\pet-project-fe\node_modules\webpack-cli\bin\utils\convert-argv.js:121:15) {
  code: 'ERR_REQUIRE_ESM'
}
error Command Failed with exit code 1.

我什至不知道使用什么“类型”以及为什么在这种情况下显然需要使用“类型”,所以我真的不想在不知道自己在做什么的情况下添加随机内容。无论如何,它还是不能解决问题,因为在运行代理时出现新错误

$ cross-env nodemon proxy/proxy
[nodemon] 2.0.4
[nodemon] to restart at any time,enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: tsx,json
[nodemon] starting `node proxy/proxy src/index.tsx`
(node:25420) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/run_main.js:54
    internalBinding('errors').triggeruncaughtException(
                              ^

TypeError [ERR_UNKNowN_FILE_EXTENSION]: UnkNown file extension ".tsx" for C:\*path to project*\pet-project-fe\src\index.tsx
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
    at Loader.getFormat (internal/modules/esm/loader.js:113:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
    at processticksAndRejections (internal/process/task_queues.js:97:5)
    at async Loader.import (internal/modules/esm/loader.js:178:17) {
  code: 'ERR_UNKNowN_FILE_EXTENSION'
}
[nodemon] app crashed - waiting for file changes before starting...

不确定这是否与TypeScript有关,但我想以防万一。

我在做什么错了?

解决方法

我终于开始工作了。

首先,我放弃了尝试使代理与.txs文件类型一起使用的尝试。因此,我选择了.js,还使用了require(...)而不是import

const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware')

const app = express()
    
app.use('/api/**',createProxyMiddleware({ target: 'http://localhost:8080',changeOrigin: true }))
app.listen(3002)

然后我意识到这一切都没有意义,因为如果我对./api进行查询,它将把它定向到实际的应用程序端口(即端口3001),因为这是我的实际应用程序在其中运行的位置

"start": "cross-env NODE_ENV=development webpack-dev-server --open --content-base ./public --port 3001",

直接调用端口3002导致失败,并且在3001上同时运行它们都使我的应用程序完全无法正常工作。因此解决方案是将其添加到webpack.config.js

config.devServer = {
  ...
  proxy: [{
    context: ['/api'],target: `http://localhost:3002`,changeOrigin: true,}],};

现在在这里稍等片刻。我为什么要这样做?为什么不立即在此处将80 proxy.js完全绕过任何端口作为目标端口……您知道什么。有用。我要做的就是添加

config.devServer = {
  ...
  proxy: [{
    context: ['/api'],target: `http://localhost:8080`,};

webpack.config.js

因此,我承认我完全不知道自己在做什么,而所有这些东西都是非常令人困惑,容易出错和复杂的。我能够从我的依赖项中删除expresshttp-middleware-proxy(开发服务器似乎可以独立获取它们)。

最后,我放弃了尝试建立自己的快速代理的过程,意识到webpack-dev-server显然已经具有代理功能,只能使用该代理,即使最终使用它,也会感到失败。 / p>