I am new to webpack and I got the babel loader and css loader to work and project compiles successfully but when I try to access via browser I get the below error. It looks
What if you were to replace %PUBLIC_URL%
with the actual path. I think that Babel is having issues transpiling the %
. Try replacing %PUBLIC_URL%/favicon.ico
with /public/favicon.ico
and the issue is resolved.
Add a new rule to your webpack.config.js.
//...
{
test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
exclude: /node_modules/,
use: ['file-loader?name=[name].[ext]'] // ?name=[name].[ext] is only necessary to preserve the original file name
}
//...
Then have the .ico resource copied to the dist directory by adding an import in your App.js. import '../public/favicon.ico';
In your index.html; <link rel="shortcut icon" href="favicon.ico">
to make use of your icon. No longer need to provide a path since it will be copied to the dist directory
OR:
In addition to the rule added to the webpack.config.js mentioned above, adding plugins to the webpack config may be a better way to go depending on your setup.
For me this looks like adding the npm package html-webpack-plugin to the project. Then requiring it in the webpack config; const HtmlWebpackPlugin = require('html-webpack-plugin');
. Then adding plugins
to the module.exports
.
//...
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: './index.html',
favicon: './public/favicon.ico'
})
]
//...
Going this route and doing the work in the webpack config means the line added to the App.js to import the favicon.ico will no longer be necessary.
EDIT: As mentioned by @Tolumide
Don't forget to configure the webpack.config appropriately per environment.
I had the same issue and fixed it with the following:
Inside webpack.config.js in the plugins
array, add HtmlWebpackPlugin
and InterpolateHtmlPlugin
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw)
This is the documentation of InterpolateHtmlPlugin
Makes some environment variables available in index.html.
The public URL is available as %PUBLIC_URL% in index.html, e.g.:
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
In production, it will be an empty string unless you specify "homepage"
in `package.json`, in which case it will be the pathname of that URL.
In development, this will be an empty string.