简体   繁体   中英

React - use relative paths to static assets in CSS

I'm using create-react-app to build an interface for an Electron app. As such, the built React app essentially runs locally rather than from a server.

Naturally I have a load of SCSS being built by React, but as part of the build process my paths are changed from url(../images/my_img.jpg) to url(/static/media/my_img.xyz.jpg)

Obviously for a server environment where files would be stored at the root this is fine, but because my files are running locally the browser (Electron) can't locate the images.

I have set "homepage": "./" in package.json but this has had no effect.

Is there a way to ensure that built CSS uses relative paths rather than absolute?

Ok, it's a bit of a hacky workaround, but for now what I've managed to do is...

1) I installed the "replace" NPM package in my project: https://www.npmjs.com/package/replace

2) I then set up a postbuild script in package.json:

"postbuild": "replace 'static' '..' build/static/css/*"

It's not ideal, but it does the job!

Try "homepage": "."

There are problems possibly to be encountered with "homepage": "." so it works in some cases, but It's not recommended.

尝试像导入模块一样导入您的 css 文件,我用它工作得很好。

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