reactjs 如何在React js with Vite的开发模式下使用json文件中的环境变量?

64jmpszr  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(146)

我创建了一个React js应用程序,其中包含Vite实现。所以现在我必须在开发模式下运行应用程序时使用json文件中的环境变量。
附上一些代码以供参考。

.环境开发

VITE_NODE_ENV=development
VITE_REACT_APP_BASE_URL = "http://localhost:3000"

vite.config.js

import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import viteTsconfigPaths from 'vite-tsconfig-paths';
import { TransformOption, viteStaticCopy } from 'vite-plugin-static-copy';

const copyPlugin = (env: any) => {
  const reactBaseURLtransform: TransformOption = (contents, path) => {
    return contents.replace(/<REACT_APP_BASE_URL>/g, env.VITE_REACT_APP_BASE_URL);
  };

  return viteStaticCopy({
    flatten: true,
    targets: [
      {
        src: 'public/*.json',
        dest: '',
        transform: reactBaseURLtransform,
      }
    ],
  });
};

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const plugins: any[] = [react(), viteTsconfigPaths()];
  plugins.push(copyPlugin(env));

  return {
    plugins: [...plugins],
    build: {
      outDir: 'build',
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
      chunkSizeWarningLimit: 5000,
    },
    server: {
      open: false,
      port: 3000,
    },
  };
});

目前使用Vite的这种配置,当我们使用yarn build(内部运行“vite build”)构建应用程序时,Vite会将所有的替换<REACT_APP_BASE_URL>为中定义的URL。env文件。
以同样的方式,当我们使用yarn start(它在内部运行“vite”)启动应用程序时,它应该将所有的替换<REACT_APP_BASE_URL>为中定义的URL。env文件,但目前它没有这样做。
那么,用<REACT_APP_BASE_URL>中定义的URL替换所有(在json文件中定义的)的方法是什么呢?当我们在开发模式下启动应用程序时,会打开env文件。

cbjzeqam

cbjzeqam1#

试试这个:

  • 创建自定义Vite插件
  • 对JSON文件使用transform钩子
  • 在开发过程中替换<REACT_APP_BASE_URL>
// Custom plugin in vite.config.js
const replaceBaseUrlPlugin = (env) => {
  return {
    name: 'replace-base-url',
    transform(code, id) {
      if (id.endsWith('.json') && env.VITE_NODE_ENV === 'development') {
        return code.replace(/<REACT_APP_BASE_URL>/g, env.VITE_REACT_APP_BASE_URL);
      }
    },
  };
};

// Add the plugin to your configuration
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const plugins: any[] = [react(), viteTsconfigPaths(), replaceBaseUrlPlugin(env)];

  // ...
});

这应该可以在开发过程中替换JSON文件中的<REACT_APP_BASE_URL>

wpcxdonn

wpcxdonn2#

我遇到的问题是我不能得到。env文件。最初是我的。env文件在src文件夹中,当我将。env文件到项目的根目录中,我才能够得到它。

相关问题