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?
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