简体   繁体   English

将 JSON 个文件包含到 React 构建中

[英]Include JSON files into React build

I know this question maybe exist in stack overflow but I didn't get any good answers, and I hope in 2020 there is better solution.我知道这个问题可能存在于 stack overflow 但我没有得到任何好的答案,我希望在 2020 年有更好的解决方案。

In my react app I have a config JSON file, it contains information like the title, languages to the website etc.. and this file is located in 'src' directory在我的 React 应用程序中,我有一个配置文件 JSON,它包含标题、网站语言等信息。这个文件位于“src”目录中

 {
  "headers":{
    "title":"chat ",
    "keys":"chat,asd  ,
    "description":" website"
  },
  "languages":{
    "ru":"russian",
    "ar":"arabic",
    "en":"English"
  },
  "defaultLanguage":"ru",
  "colors":{
    "mainColor":"red",
    "primary":"green",
    "chatBackGround":"white"
  }
}

I want to make my website easy to edit after publishing it, but after I build my app, I can't find that settings.json file there in build directory.我想让我的网站在发布后易于编辑,但在构建我的应用程序后,我无法在构建目录中找到 settings.json 文件。

I find out that files in public directory actually get included to build folder, I tried to put my settings.JSON in public, but react won't let me import anything outside of src directory我发现 public 目录中的文件实际上包含在 build 文件夹中,我试图将我的 settings.JSON 公开,但 React 不允许我导入 src 目录之外的任何内容

I found other solutions like this one but didn't work https://github.com/facebook/create-react-app/issues/5378我找到了其他类似的解决方案,但没有用 https://github.com/facebook/create-react-app/issues/5378

Also I tried to create in index.html a global var like (window.JSON_DATA={}), and attach a JS object to it and import it to App.js, but still didn't work.我还尝试在 index.html 中创建一个全局变量,如 (window.JSON_DATA={}),并将 JS object 附加到它并将其导入 App.js,但仍然没有用。

How can I make a settings JSON file, and have the ability to edit it after publishing the app?如何制作设置 JSON 文件,并在发布应用程序后能够对其进行编辑?

Add your settings.json to the public folder.将您的settings.json添加到public React will copy the file to the root of build. React 会将文件复制到构建的根目录。 Then load it with fetch where you need it to be used.然后在需要使用它的地方使用fetch加载它。 For example if you need to load setting.json to the App.js then do the next:例如,如果您需要将setting.json加载到App.js ,然后执行以下操作:

function App() {

    const [state, setState] = useState({settings: null});

    useEffect(()=>{
        fetch('settings.json').then(response => {
            response.json().then(settings => {
                // instead of setting state you can use it any other way
                setState({settings: settings});
            })
        })
    })
}

If you use class-components then do the same in componentDidMount :如果您使用类组件,则在componentDidMount中执行相同操作:

class CustomComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {settings: null};
    }

    componentDidMount() {
        fetch('settings.json').then(response => {
            response.json().then(settings => {
                this.setState({settings: settings});
            })
        })            
    }
}

Then you can use it in render (or any other places of your component):然后您可以在渲染(或组件的任何其他位置)中使用它:

function App() {

    ...

    return (
        {this.state.settings && this.state.settings.value}
    ) 
}

You may want to look at using npm react-scripts ( https://www.npmjs.com/package/react-scripts ) to produce your react application and build.您可能想查看使用 npm react-scripts ( https://www.npmjs.com/package/react-scripts ) 来生成您的反应应用程序和构建。 This will package will create a template that you can put your existing code into and then give you a pre-configure build option that you can modify if you would like.这将 package 将创建一个模板,您可以将现有代码放入其中,然后为您提供预配置构建选项,您可以根据需要进行修改。 The pre-configured build option will package your.json files as well.预配置的构建选项也将 package your.json 文件。 Check out their getting started section ( https://create-react-app.dev/docs/getting-started/ )查看他们的入门部分( https://create-react-app.dev/docs/getting-started/

If you don't want to go that route, and are just looking for quick fix, then I would suggest change your json files to a JS file, export the JS object and import it in the files you need it since you seem to be able to do that.如果您不想 go 这条路线,并且只是在寻找快速修复,那么我建议将您的 json 文件更改为 JS 文件,导出 JS object 文件,因为您似乎将它导入您需要的文件中能够做到这一点。

//src/sampledata.js
module.exports = {
  sample: 'data'
}
//src/example.jsx (this can also be .js)
const sampledata = require('./sampledata');
console.log(sampledata.sample); // 'data'

you can use 'Fetch Data from a JSON File' according to link https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app example您可以根据链接https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app示例使用“从 JSON 文件中获取数据”

The easiest way would be to require() the file on the server during server side rendering of the html page and then inline the json in the html payload in a global var like you mentioned window.JSON_DATA={} . The easiest way would be to require() the file on the server during server side rendering of the html page and then inline the json in the html payload in a global var like you mentioned window.JSON_DATA={} . Then in your js code you can just reference that global var instead of trying to use import .然后在您的 js 代码中,您可以只引用该全局 var 而不是尝试使用import

Of course this approach would require you to restart your server every time you make a change to the json file, so that it get's picked up.当然,这种方法需要您在每次更改 json 文件时重新启动服务器,以便获取它。 If that is not an option then you'll need to make an api call on the server instead of using require() .如果这不是一个选项,那么您需要在服务器上进行 api 调用,而不是使用require()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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