create-react-app的打包后index頁面內引用其他資源的路徑問題


在使用create react build項目時,發現build的目錄內的js,css引用使用的地址前面使用的是/XXX而不是./XXX這就導致了引用資源的地址無效

/  表示根目錄

./ 表示當前目錄

../表示父級目錄

修復方法有多種:

最簡單的是在package.json內定義一個 

"homepage":"."
即可
 

如:A different way to handle this is to do a rename as a part of your build process with a new npm run script so you don't have to do an eject. I used the renamer npm library to do this for me.

npm install --save-dev renamer

Then in package.json scripts section I added some rename helpers:

    "build-rename": "npm run build-rename-js && npm run build-rename-css",
    "build-rename-js": "renamer --regex --find 'main\\.[^\\.]+\\.js' --replace 'main.js' build/static/js/*.js",
    "build-rename-css": "renamer --regex --find 'main\\.[^\\.]+\\.css' --replace 'main.css' build/static/css/*.css",

then you can modify your build script to do the rename post-build like this:

"build": "react-scripts build && npm run build-rename",

Anyways, this is just one way to do it. You will give up source maps unless you do a search and replace inside the js file, but in your specific case of putting on a mobile device that probably doesn't matter.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM