Add Favicon with React and Webpack

我试图添加一个图标的反应为基础的网站,我使用网络包。这是一个完全的噩梦,添加一个图标,我已经尝试了很多解决方案,但无济于事。推荐给我的最新解决方案是“ Favicon-webpack-plugin”,可以在这里找到: https://github.com/jantimon/favicons-webpack-plugin

如果有人能告诉我我做错了什么,我将不胜感激。

当我运行‘ npm run start’时,我得到以下错误

enter image description here

这是我的目录结构:

enter image description here

这是我的 webpack.config.js 文件:

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const TARGET = process.env.npm_lifecycle_event;
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var favicons = require('favicons'),
source = 'my-logo.png',           // Source image(s). `string`, `buffer` or array of `{ size: filepath }`
configuration = {
appName: null,                  // Your application's name. `string`
appDescription: null,           // Your application's description. `string`
developerName: null,            // Your (or your developer's) name. `string`
developerURL: null,             // Your (or your developer's) URL. `string`
background: "#fff",             // Background colour for flattened icons. `string`
path: "/",                      // Path for overriding default icons path. `string`
url: "/",                       // Absolute URL for OpenGraph image. `string`
display: "standalone",          // Android display: "browser" or "standalone". `string`
orientation: "portrait",        // Android orientation: "portrait" or "landscape". `string`
version: "1.0",                 // Your application's version number. `number`
logging: false,                 // Print logs to console? `boolean`
online: false,                  // Use RealFaviconGenerator to create favicons? `boolean`
icons: {
android: true,              // Create Android homescreen icon. `boolean`
appleIcon: true,            // Create Apple touch icons. `boolean`
appleStartup: true,         // Create Apple startup images. `boolean`
coast: true,                // Create Opera Coast icon. `boolean`
favicons: true,             // Create regular favicons. `boolean`
firefox: true,              // Create Firefox OS icons. `boolean`
opengraph: true,            // Create Facebook OpenGraph image. `boolean`
twitter: true,              // Create Twitter Summary Card image. `boolean`
windows: true,              // Create Windows 8 tile icons. `boolean`
yandex: true                // Create Yandex browser icon. `boolean`
}
},
callback = function (error, response) {
if (error) {
console.log(error.status);  // HTTP error code (e.g. `200`) or `null`
console.log(error.name);    // Error name e.g. "API Error"
console.log(error.message); // Error description e.g. "An unknown error has occurred"
}
console.log(response.images);   // Array of { name: string, contents: <buffer> }
console.log(response.files);    // Array of { name: string, contents: <string> }
console.log(response.html);     // Array of strings (html elements)
};


favicons(source, configuration, callback);
const pkg = require('./package.json');


const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build')
};


process.env.BABEL_ENV = TARGET;


const common = {
entry: {
app: PATHS.app
},
// Add resolve.extensions
// '' is needed to allow imports without an extension
// note the .'s before the extension as it will fail to load without them
resolve: {
extensions: ['', '.js', '.jsx', '.json']
},
output: {
path: PATHS.build,
filename: 'bundle.js'
},
module: {
loaders: [
{
// Test expects a RegExp! Notethe slashes!
test: /\.css$/,
loaders: ['style', 'css'],
//Include accepts either a path or an array of paths
include: PATHS.app


},
//set up JSX. This accepts js too thanks to RegExp
{
test: /\.(js|jsx)$/,
//enable caching for improved performance during development
//It uses default OS directory by default. If you need something more custom,
//pass a path to it. ie: babel?cacheDirectory=<path>
loaders: [
'babel?cacheDirectory,presets[]=es2015'
],
//parse only app files Without this it will go thru the entire project.
//beside being slow this will likely result in an error
include: PATHS.app
}
]
}
};


// Default configuration. We will return this if
// Webpack is called outside of npm.
if(TARGET === 'start' || !TARGET){
module.exports = merge(common, {
devtool: 'eval-source-map',
devServer: {
contentBase: PATHS.build,


//enable history API fallback so HTML5 HISTORY API based
// routing works. This is a good default that will come in handy in more
// complicated setups.
historyApiFallback: true,
hot: true,
inline: true,
progress: true,


//display only errors to reduce output amount
stats: 'errors only',


//Parse host and port from env so this is easy to customize
host: process.env.HOST,
port: process.env.PORT


},


plugins: [
new webpack.HotModuleReplacementPlugin(),
new NpmInstallPlugin({
save: true //--save
}),
new FaviconsWebpackPlugin('my-logo.png')


]
});
}


if(TARGET === 'build' || TARGET === 'stats') {
module.exports = merge(common, {
entry: {
vendor: Object.keys(pkg.dependencies).filter(function(v) {
return v !== 'alt-utils';
}),
style: PATHS.style
},
output: {
path: PATHS.build,
// Output using entry name
filename: '[name].[chunkhash].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
// Extract CSS during build
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css'),
include: PATHS.app
}
]
},
plugins: [
// Output extracted CSS to a file
new ExtractTextPlugin('[name].[chunkhash].css'),
// Extract vendor and manifest files
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
// Setting DefinePlugin affects React library size!
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
});
}

这是我的 server.js 文件:

/* Global Requires */


const express    = require('express');
const logger     = require('morgan');
const bodyParser = require('body-parser');
const path       = require('path');
const app        = express();
const ReactDOM = require('react-dom')
var favicon = require('serve-favicon');




if(process.env.NODE_ENV === 'development') {
console.log('in development.');
require('dotenv').config();
} else {
console.log('in production.');
}


/* App Config */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'build')));
app.use(favicon(__dirname + '/public/favicon.ico'));


app.use(logger('dev'));


/* Server Initialization */
app.get('/', (req, res) => res.sendFile('index.html'));
var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server initialized on // ${new Date()}`));
165198 次浏览

浏览器在 /favicon.ico中寻找您的收藏夹图标,所以这就是它需要的位置。您可以通过导航到 [address:port]/favicon.ico并查看您的图标是否出现,再次检查是否将其放置在正确的位置。

在 dev 模式下,您正在使用 history yApiFallback,因此需要配置 webpack 来显式返回该路由的图标:

historyApiFallback: {
index: '[path/to/index]',
rewrites: [
// shows favicon
{ from: /favicon.ico/, to: '[path/to/favicon]' }
]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(或者您的安装程序更喜欢重写 url)

我建议生成一个真正的 .ico文件,而不是使用 .png,因为我发现在不同的浏览器中使用 .png更可靠。

简单地将您的图标添加到 public文件夹中就可以了。请确保图标名为 favicon.ico

For future googlers: 您还可以使用 Copy-webpack-plugin 复制-网络包-插件并将其添加到 webpack 的生产配置中:

plugins: [
new CopyWebpackPlugin({
patterns: [
// relative path is from src
{ from: './static/favicon.ico' }, // <- your path to favicon
]
})
]

使用 文件加载程序:

{
test: /\.(svg|png|gif|jpg|ico)$/,
include: path.resolve(__dirname, path),
use: {
loader: 'file-loader',
options: {
context: 'src/assets',
name: 'root[path][name].[ext]'
}
}
}

另一个选择是

npm install react-favicon

在你的申请中,你只需要做:

   import Favicon from 'react-favicon';
//other codes


ReactDOM.render(
<div>
<Favicon url="/path/to/favicon.ico"/>
// do other stuff here
</div>
, document.querySelector('.react'));

它与添加任何其他外部脚本或样式表相同。 你所要做的就是专注于给予 正确的路径Rel类型

注意: 当我的图标图像是在 资产文件夹,它是 not displaying the favicon。所以我的 将图像复制到 index.html 的相同文件夹中和它完美地工作,因为它应该。

<head>
<link rel="shortcut icon" type="image/png/ico" href="/favicon.png" />
<title>SITE NAME</title>
</head>

对我有用,希望对你也有用。

我是这么做的。

Public/index.html

我已经添加了生成的图标链接。

...
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/path/to/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/path/to/favicon-16x16.png" />
<link rel="shortcut icon" href="%PUBLIC_URL%/path/to/favicon.ico" type="image/png/ico" />

webpack.config.js

new HTMLWebpackPlugin({
template: '/path/to/index.html',
favicon: '/path/to/favicon.ico',
})

注意

我在开发模式下使用 historyApiFallback,但是我不需要任何额外的设置来使图标工作,也不需要在服务器端。

以下是你所需要的:

new HtmlWebpackPlugin({
favicon: "./src/favicon.gif"
})

这肯定是在将“ Favicon.gif”添加到文件夹“ src”之后。

This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">. This is safer than just importing with copyWebpackPLugin

我将给出添加图标的简单步骤: -)

  • Create your logo and save as logo.png
  • Change logo.png to favicon.ico

    注意 :,当你保存它是 favicon.ico,确保它不是 favicon.ico.png

  • 可能需要一些时间来更新

    如果您不能等待,请更改 Manif.json 中的图标大小

在我的例子中——我使用 webpack 2.4.1在调试模式下运行 Visual Studio (Professional 2017)——有必要将 favicon.ico放到项目的根目录中,就是文件夹 src所在的位置,而不是 public文件夹,尽管根据 https://create-react-app.dev/docs/using-the-public-folder,后者应该是官方位置。

我用 图标-网络包-插件

const FaviconsWebpackPlugin = require("favicons-webpack-plugin");


module.exports={
plugins:[
new FaviconsWebpackPlugin("./public/favicon.ico"),
//public is in the root folder in this app.


]
}

正确答案:

如果你直接使用 webpack:

new HtmlWebpackPlugin({
favicon: "./public/fav-icon.ico"
})

如果您使用 CRA (create-response-app) ,那么您可以修改 public 目录中的 manifest.json

This worked for me. Add the following in index.html (inside src folder along with favicon.ico)

<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />

webpack.config.js中添加到您的插件

 plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],

Replace the favicon.ico in your public folder with yours, that should get you going.

清除浏览器缓存

对于任何仍在搜索... 我设法在我的 index.html 中导入图标,一旦我运行
npm install html-loader
在我的 webpack.config.js中包括以下内容:

// ... Other config options.
{
test: /\.html$/,
include: path.resolve(__dirname, 'public'), // Your path may be different.
use: [
{
loader: 'html-loader',
},
],
},

文件路径需要与源代码相关,而不是与生产代码相关。 为了检查您的构建是否包含图标,您可以在 URL 中查找生产路径,如下所示: localhost:xxxxx/path/to/favicon.png

I believe the answers mentioning CopyWebpackPlugin and HtmlWebpackPlugin are both adequate.

然而,有两点值得注意:

  1. CopyWebpackPlugin is a 由社区成员维护的第三方软件包,可能不具备与 webpack 相同的支持、安全策略或许可,也不由 webpack 维护 - Hence why there are comments saying it is less safe.

  2. The benefit of using CopyWebpackPlugin is that you can specify the output folder (i.e. /public/images - This will place your favicon in 远距离/公开/图像 and your HTML file can access it there). HtmlWebpackPlugin will put the favicon in the root of the dist folder, meaning less flexibility in your input of how the 远离 folder is structured.