URIError: Failed to decode param '/%PUBLIC_URL%/favicon.ico'

前端 未结 2 791
忘了有多久
忘了有多久 2021-01-11 13:28

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

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 14:03

    Quick fix

    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.

    Better fix

    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; 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.

提交回复
热议问题