Reputation: 2089
How can we remove the initial slash from all the files included automatically in index.html
from webpack (like <script src="/static/js/...">
...) and all the paths of a react app?
How is possible to customize the webpack.config.js
in a react project created by the command line npx create-react-app
without ejecting it?
Upvotes: 1
Views: 2223
Reputation: 31
Part 1 of Fancesco Orsi's answer fixed part of my problem, but the /static/
appears to require messing with configs or adding libraries.
It was simpler to botch together a postscript that runs between my react and electron build. I'm sure people could repurpose this for what they need.
I made a JavaScript file with the following code and pointed a post-script in package.json
to it.
"postbuild": "node mid-build.js"
const { readFileSync, writeFileSync } = require('fs');
let txt = readFileSync('./build/index.html');
txt = txt.toString().replaceAll('/static/', 'static/');
writeFileSync('./build/index.html', txt);
console.log('\nmid-build edits complete\n');
Not elegant, but it works and I can get back to debugging builds.
Upvotes: 2
Reputation: 2089
open the public/index.html
removing all the slashes after/before %PUBLIC_URL%
for example
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
become
<link rel="icon" href="%PUBLIC_URL%favicon.ico" />
if you use the variable process.env.PUBLIC_URL
in your jsx, remove always the slash after/before the variable.
for example
const json = await http({ url: `${process.env.PUBLIC_URL}/config.json`});
become
const json = await http({ url: `${process.env.PUBLIC_URL}config.json`});
Create a empty file in the root of the project called .env
entering this text:
PUBLIC_URL=
to replace the publicPath
value of the webpack.config.js
(you normally find this file in /node_modules/react-scripts/config/webpack.config.js
) without touching the original (it is not recommended!!) you can use a library like react-app-rewired
or craco
.
Below you can see an example with craco https://www.npmjs.com/package/@craco/craco :
After the installation by npm i @craco/craco
you need to replace some lines of your package.json
from
...
"scripts": {
"start": "react-script start",
"build": "react-script build",
"test": "react-script test",
"eject": "react-script eject"
},
...
to
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "craco eject"
},
...
after that, in your root project add a file called craco.config.js
inside the file add the following code
module.exports = {
configure: {
output: {
publicPath: ''
}
}
}
}
that's it
Upvotes: 1