webpack v4.20.2
webpack-dev-server v3.1.9
I'm running a react application with webpack
and webpack-dev-server
and meet a problem about %PUBLIC_URL%
.
URIError: Failed to decode param '/%PUBLIC_URL%/favicon.ico'
The %PUBLIC_URL%
hadn't been compiled in index.html, so failed to get the favicon.
public/index.html
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
</head>
package.json scripts
"scripts": {
"dev": "webpack-dev-server --config ./config/webpack.dev.conf.js --open",
"build": "webpack --config ./config/webpack.prod.conf.js"
},
project structure
.
├── config
│ ├── webpack.dev.conf.js
│ └── webpack.prod.conf.js
├── public
│ ├── index.html
│ ├── favicon.ico
│ └── manifest.json
├── src
│ ├── index.js
│ ...
└── package.json
webpack.dev.conf.js
module.exports = {
mode: 'development',
entry: ['babel-polyfill', './src/index.js'],
output: {
filename: '[name].bundle.[hash].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
devtool: 'source-map',
devServer: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
secure: false,
},
},
publicPath: '/',
},
module: {
rules: [
// styles
{
test: /\.(s)css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]--[hash:base64:5]',
},
},
{
loader: 'postcss-loader',
options: {
plugins() {
return [autoprefixer()]
},
sourceMap: true,
},
},
'sass-loader',
],
},
// javascripts
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
plugins: [['import', { libraryName: 'antd' }]],
},
},
exclude: /node_modules/,
},
// images
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
context: 'src',
outputPath: 'assets/',
},
},
],
},
// htmls
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
new HtmlWebpackPlugin({
template: './public/index.html',
filename: './index.html',
}),
],
...
}
Does it related to the publicPath
field in the config file?
How can I fix the error in webpack.dev.conf.js
and webpack.prod.conf.js
?
For someone who needs it. Using this plugin interpolate-html-plugin (extract from react-scripts)
Step 1:
npm install interpolate-html-plugin --save-dev
Step 2:
At plugins of webpack config add this plugin into it like that.
new InterpolateHtmlPlugin({
PUBLIC_URL: 'static' // can modify `static` to another name or get it from `process`
})
Step 3:
Run the project and it works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With