使用React viteJS构建问题,并被放大



我的问题很容易解释。我已经用ViteJS初始化了一个React项目,然后为后端添加了aws-amplifier。我开发了这个项目,所有的东西都在我的本地环境中运行npm-run-dev。问题是我无法构建它。你可以在下面的文本中看到错误。你知道吗?

'request'不由__vite-browser-external导出,由node_modules/@aws-sdk/credential provider imds/dist/es/remoteProvider/httpRequest.js 导入

错误日志

在vite.config.js中添加:

resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
}

定义字段

用于AWS SDK和Amplify 的React polyfilled的工作配置

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis", //<-- AWS SDK 
},
},
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
},
},
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser', // <-- Fix from above
},
}
});

使用别名数组时。


resolve: {
alias: [
{
find: '@', replacement: path.resolve(__dirname, './src'),
},
{
find: './runtimeConfig', replacement: './runtimeConfig.browser',
}
]
}

对于问题"'请求'未由__vite-browser-external导出";,只需安装http包(例如"npm i http"(

这类问题的根本原因似乎是aws-amplifyJS lib依赖于Node特定的功能。有两个部分的解决方法:

  1. 若要解决类似'xxxxx' is not exported by __vite-browser-external的错误,请将./runtimeConfig的附加别名添加到vite.config.ts文件中。所以它看起来像:
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
'./runtimeConfig': './runtimeConfig.browser',
},
  1. 若要解决类似Uncaught ReferenceError: global is not defined的错误,请在最顶层的html文件(index.html(中声明相应的全局变量
<script>
var global = global || window;
var Buffer = Buffer || [];
var process = process || {
env: { DEBUG: undefined },
version: []
};
</script>

github问题已经公开一年多了:https://github.com/aws-amplify/amplify-js/issues/9639

最新更新