Different ways to import files in React

别来无恙 提交于 2019-12-11 00:25:21

问题


currently the way I import files in the client folder of a react app is to use import statement which I believe uses Webpack. e.g.

import cat_png from '../../game_book/images/cat.png';

This has its limitation because of Webpack configuration.....

I was wondering if there is a different way to access files in the React project....

My problem with the current way of importing is that if I import a png it does give me a static link e.g.

localhost:8000/static/media/cat.png

but when I import a json file import animals_json from '../../game_book/images/animals.json'; I DO NOT get

localhost:8000/static/media/animals.json

But the actual contents of the json e.g.

{frames:....}

What I need is a consistent way to access assets inside a folder in the client folder of my react app.... Therefore if I have a json file I want to be able to access via ./myassets/animals.json or if it an image ./myassets/myimage.png etc. Just like when I'm using a plain html file without React....I can access the folder that is inside the same folder as the html file via ./foldername and then if there is a myimage.png inside the foldername then I can access it via ./foldername/myimage.png

What options do I have? Can I create my own static media link using React-router?


回答1:


This is because of the actions of different loaders in your configuration, images are handled by url-loader and file-loader which gives you either a URL or a base64 data path. JSON is loaded by a json-loader which gets you the contents as an object.

If you need to import these assets into webpack and get their URLs you would have to modify the loaders to do so. But if you just need to use the URLs to assets, you can use the public folder.

If you put a file into the public folder, it will not be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the public folder, you need to use a special variable called PUBLIC_URL.

Inside index.html, you can use it like this:

<link rel="icon" href="%PUBLIC_URL%/favicon.ico">

Different shortcomings and benifits are discussed in docs



来源:https://stackoverflow.com/questions/58280154/different-ways-to-import-files-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!