简体   繁体   中英

Sharing a configuration file between Python and a React project created with create-react-app

I need to share a configuration file between Python and React code - I could use JSON, which is easy to import into each, but I'd prefer to be able to add comments, turn parts on and off, etc.

What is a good way of doing something like this?

I've been trying out HJSON (human-readable JSON) , but bundling a text file like HJSON into the React build doesn't work AFAIK without ejecting create-react-app and modifying the webpack config to use raw-loader , or using react-app-rewired to do something similar.

I wound up using react-app-rewired -

First add these libraries to the React project -

yarn add react-app-rewired
yarn add hjson
yarn add hjson-loader

Then add a config-overrides.js file to the top level of the React project - this will modify the webpack config on the fly -

const { getLoader } = require('react-app-rewired');

function rewireAddHjson(config, env, options = {}) {
  const hjsonExtension = /\.hjson$/;
  const excludeRule = getLoader(config.module.rules, rule => rule.exclude);
  excludeRule.exclude.push(hjsonExtension);
  const hjsonRule = {
    test: hjsonExtension,
    loader: 'hjson-loader',
  };
  config.module.rules.push(hjsonRule);
  return config;
}

module.exports = function override(config, env) {
  config = rewireAddHjson(config, env);
  return config;
};

and in package.json replace "react-scripts" with "react-app-rewired":

"scripts": {
-   "start": "react-scripts start",
-   "build": "react-scripts build",
-   "test": "react-scripts test --env=jsdom",
+   "start": "react-app-rewired start",
+   "build": "react-app-rewired build",
+   "test": "react-app-rewired test --env=jsdom"
}

Then in Python you can say

import hjson
with open('app/client/src/assets/options.hjson') as f:
    options = hjson.load(f)

and in React can say

import options from '../assets/options.hjson'; // a json object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM