URIError: Не удалось декодировать параметр '/%PUBLIC_URL%/favicon.ico' - PullRequest
0 голосов
/ 12 июня 2018

Я новичок в веб-пакете и получил загрузчик babel и загрузчик css, и проект успешно компилируется, но когда я пытаюсь получить доступ через браузер, я получаю следующую ошибку.Похоже, что PUBLIC_URL не распознается.Мне кажется, я не знаю, как это настроить.

Я ценю ваши ценные комментарии.

Спасибо

ℹ 「wdm」: Compiled successfully. URIError: Failed to decode param 
'/%PUBLIC_URL%/favicon.ico' at decodeURIComponent (<anonymous>) at 
decode_param (/home/mike/finance- 
grapher/node_modules/express/lib/router/layer.js:172:12) at Layer.match 
(/home/mike/finance- 
grapher/node_modules/express/lib/router/layer.js:123:27) at matchLayer 
(/home/mike/finance- 
grapher/node_modules/express/lib/router/index.js:574:18) at next 
(/home/mike/finance- 
grapher/node_modules/express/lib/router/index.js:220:15) at expressInit 
(/home/mike/finance- 
grapher/node_modules/express/lib/middleware/init.js:40:5) at Layer.handle 
[as handle_request] (/home/mike/finance- 
grapher/node_modules/express/lib/router/layer.js:95:5) at trim_prefix 
(/home/mike/finance- 
grapher/node_modules/express/lib/router/index.js:317:13) at 
/home/mike/finance-grapher/node_modules/express/lib/router/index.js:284:7 
at Function.process_params (/home/mike/finance- 
grapher/node_modules/express/lib/router/index.js:335:12)

Webpack.config.js

.babelrc

package.json

структура папки проекта

Ответы [ 2 ]

0 голосов
/ 07 июня 2019

У меня была та же проблема, и я исправил ее следующим образом:

Внутри webpack.config.js в массиве plugins добавьте HtmlWebpackPlugin и 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)

Это документация 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.
0 голосов
/ 30 сентября 2018

Быстрое исправление

Что делать, если вы должны заменить %PUBLIC_URL% на фактический путь.Я думаю, что у Вавилона проблемы с транспортом %.Попробуйте заменить %PUBLIC_URL%/favicon.ico на /public/favicon.ico, и проблема будет решена.

Лучшее исправление

Добавьте новое правило в ваш 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
}
//...

Затем скопируйте ресурс .ico в каталог dist , добавив импорт в App.js .import '../public/favicon.ico';

В вашем index.html;<link rel="shortcut icon" href="favicon.ico"> чтобы использовать вашу иконку.Больше нет необходимости указывать путь, поскольку он будет скопирован в каталог dist

ИЛИ:

В дополнение к правилу, добавленному в webpack.config.js упоминалось выше, добавление плагинов в конфигурацию веб-пакета может быть лучшим способом в зависимости от ваших настроек.

Для меня это выглядит как добавление пакета npm html-webpack-plugin к проекту.Затем требуется это в конфиге веб-пакета;const HtmlWebpackPlugin = require('html-webpack-plugin');.Затем добавление plugins к module.exports.

//...
plugins: [
  new HtmlWebpackPlugin({
    template: './public/index.html',
    filename: './index.html',
    favicon: './public/favicon.ico'
  })
]
//...

. Переход по этому маршруту и ​​выполнение работы в конфигурации веб-пакета означает, что строка, добавленная в App.js для импорта значка.ico больше не понадобится.

...