react如何配置打包后的config.js文件

react如何配置打包后的config.js文件?
这样在修改一些特定信息(比如说接口网址),只需要修改config文件,不需要重新打包

你好,你这个需求我刚好也在使用,步骤是:在public目录下自己新建一个config.js,这个目录就是会被直接打包进去的,然后在代码里面读取这个配置,看我以下的截图

img

img


用的时候通过window去获取,一定不要忘了像我一样用Object.freeze哦,要不然别人可以在浏览器随意修改的。

打包就是根据config.js打包的吧,如果只改config不重新打包也没意义吧

那你就得全局搜了,你打包好的东西里面就已经没有配置文件这回事了。
你如果想改里面的数据 那你只能去读源码,改里面的源码信息

Create config.js or json file outside src directory and include it in index.html like

<script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>

configure parameters in config.js

var BASE_URL = "http://YOUR-URL";

you can get paramenters like

const BASE_URL = window.BASE_URL;

参考如下,有帮助的话记得采纳一下哦!
在 React 项目中,你可以将配置信息放在一个独立的文件中,在打包之前或之后加载。
其中一种方法是在打包之前使用一些工具(如 webpack)来加载并使用配置文件。这样,就只需要在开发环境和生产环境中使用不同的配置文件即可。
首先, 在项目根目录下创建一个 config.js 文件, 包含你的配置信息:

// config.js
module.exports = {
  apiUrl: 'https://example.com/api'
}

然后, 在项目中引用此配置文件, 通常是在 index.js 或 app.js

import config from './config';
console.log(config.apiUrl);

接着,您可以使用 webpack 的环境变量来区分开发环境和生产环境。 比如在 package.json 中加入:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build:prod": "react-scripts build && cross-env NODE_ENV=production webpack --config webpack.config.js",
    "test": "react-scripts test"
  },

在 webpack.config.js 中添加配置:

const path = require('path');
const { DefinePlugin } = require('webpack');
const env = process.env.NODE_ENV;
const config = require('./config');

module.exports = {
  // ...
  plugins: [
    new DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(env),
        'API_URL': JSON.stringify(config.apiUrl),
      },
    }),
  ],
};

最后,在 React 代码中引用:

import config from './config';
console.log(process.env.API_URL);

参考这个实例:https://www.cnblogs.com/wang622/archive/2022/08/08/16563991.html
该实例讲解详细,思路清晰