使用 React 和 Webpack 添加 Favicon [英] Add Favicon with React and Webpack
问题描述
我正在尝试将网站图标添加到我使用 webpack 创建的基于 React 的网站.添加网站图标完全是一场噩梦,我尝试了很多解决方案都无济于事.向我推荐的最新解决方案称为favicons-webpack-plugin",可以在这里找到:
这是我的目录结构:
这是我的 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',//源图片.`string`、`buffer` 或 `{ size: filepath }` 数组配置 = {appName: null,//您的应用程序名称.`字符串`appDescription: null,//你的应用程序的描述.`字符串`developerName: null,//您(或您的开发人员)的姓名.`字符串`developerURL: null,//您(或您的开发人员)的 URL.`字符串`background: "#fff",//扁平图标的背景颜色.`字符串`path: "/",//覆盖默认图标路径的路径.`字符串`url: "/",//OpenGraph 图像的绝对 URL.`字符串`display: "standalone",//安卓显示:"浏览器"或"独立".`字符串`方向:肖像",//Android方向:肖像"或风景".`字符串`version: "1.0",//你的应用程序的版本号.`数字`logging: false,//将日志打印到控制台?`布尔`online: false,//使用 RealFaviconGenerator 创建网站图标?`布尔`图标:{android: true,//创建 Android 主屏幕图标.`布尔`appleIcon: true,//创建苹果触摸图标.`布尔`appleStartup: true,//创建 Apple 启动图像.`布尔`Coast: true,//创建 Opera Coast 图标.`布尔`favicons: true,//创建常规的 favicon.`布尔`firefox: true,//创建 Firefox OS 图标.`布尔`opengraph: true,//创建 Facebook OpenGraph 图像.`布尔`twitter: true,//创建 Twitter 摘要卡图像.`布尔`windows: true,//创建 Windows 8 磁贴图标.`布尔`yandex: true//创建 Yandex 浏览器图标.`布尔`}},回调 = 函数(错误,响应){如果(错误){控制台日志(错误.状态);//HTTP 错误代码(例如`200`)或`null`控制台日志(错误名称);//错误名称,例如API 错误"控制台日志(错误消息);//错误描述出现未知错误"}控制台日志(响应.图像);//{名称:字符串,内容:<buffer>的数组}控制台日志(响应文件);//{名称:字符串,内容:<字符串>的数组}控制台日志(响应.html);//字符串数组(html 元素)};图标(源,配置,回调);const pkg = require('./package.json');常量路径 = {应用程序:path.join(__dirname, 'app'),构建:path.join(__dirname, 'build')};process.env.BABEL_ENV = 目标;const 公共 = {入口: {应用程序:PATHS.app},//添加resolve.extensions//需要 '' 以允许没有扩展名的导入//注意扩展名前的 . ,因为没有它们将无法加载解决: {扩展名:['', '.js', '.jsx', '.json']},输出: {路径:PATHS.build,文件名:'bundle.js'},模块: {装载机: [{//测试需要一个 RegExp!注意斜线!测试:/.css$/,加载器:['样式','css'],//Include 接受一个路径或一个路径数组包括:PATHS.app},//设置JSX.由于 RegExp,这也接受 js{测试:/.(js|jsx)$/,//在开发过程中启用缓存以提高性能//默认使用默认的OS目录.如果您需要更多定制的东西,//传递一个路径给它.即: babel?cacheDirectory=装载机: ['babel?cacheDirectory,presets[]=es2015'],//仅解析应用程序文件 如果没有这个,它将贯穿整个项目.//除了缓慢之外,这可能会导致错误包括:PATHS.app}]}};//默认配置.我们会退回这个如果//Webpack 在 npm 之外被调用.if(TARGET === '开始' || !TARGET){module.exports = 合并(普通,{开发工具:'评估源地图',开发服务器:{contentBase: PATHS.build,//启用历史API回退所以基于HTML5 HISTORY API//路由工作.这是一个很好的默认设置,在更多情况下会派上用场//复杂的设置.historyApiFallback: 真,热:真的,内联:真实,进度:真实,//只显示错误以减少输出量统计数据:'仅错误',//从env解析主机和端口,这样很容易定制主机:process.env.HOST,端口:process.env.PORT},插件: [新的 webpack.HotModuleReplacementPlugin(),新的 NpmInstallPlugin({保存:真//--保存}),新的 FaviconWebpackPlugin('my-logo.png')]});}if(TARGET === 'build' || 目标 === 'stats') {module.exports = 合并(普通,{入口: {供应商:Object.keys(pkg.dependencies).filter(function(v) {返回 v !== 'alt-utils';}),风格:PATHS.style},输出: {路径:PATHS.build,//使用条目名称输出文件名:'[名称].[chunkhash].js',chunkFilename: '[chunkhash].js'},模块: {装载机: [//在构建期间提取 CSS{测试:/.css$/,加载器:ExtractTextPlugin.extract('style', 'css'),包括:PATHS.app}]},插件: [//将提取的 CSS 输出到文件中new ExtractTextPlugin('[name].[chunkhash].css'),//提取供应商和清单文件新的 webpack.optimize.CommonsChunkPlugin({名称:['供应商','清单']}),//设置 DefinePlugin 会影响 React 库的大小!新的 webpack.DefinePlugin({'process.env.NODE_ENV': '"生产"'}),新的 webpack.optimize.UglifyJsPlugin({压缩:{警告:错误}})]});}
这是我的 server.js 文件:
/* 全局要求 */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');如果(process.env.NODE_ENV === '发展'){console.log('正在开发中.');require('dotenv').config();} 别的 {console.log('生产中.');}/* 应用配置 */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'));/* 服务器初始化 */app.get('/', (req, res) => res.sendFile('index.html'));var port = process.env.PORT ||3000;app.listen(port, () => console.log(`服务器初始化于//${new Date()}`));
这里有你需要的一切:
new HtmlWebpackPlugin({网站图标:./src/favicon.gif"})
那肯定是在将favicon.gif"添加到src"文件夹之后.
这会将图标传输到您的构建文件夹并将其包含在您的标签中,就像这样<link rel="shortcut icon" href="favicon.gif">
.这比仅使用 copyWebpackPLugin
I am attempting to add a favicon to a React-based website that I made using webpack. It has been a total nightmare to add a favicon and I have tried many solutions to no avail. The latest solution that has been recommended to me is called 'favicons-webpack-plugin' which can be found here: https://github.com/jantimon/favicons-webpack-plugin.
If anyone can tell me what I am doing wrong, your assistance would be greatly appreciated.
I get the following error when I run 'npm run start'
This is my directory structure:
This is my webpack.config.js file:
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
}
})
]
});
}
This is my server.js file:
/* 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()}`));
Here is all you need:
new HtmlWebpackPlugin({
favicon: "./src/favicon.gif"
})
That is definitely after adding "favicon.gif" to the folder "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
这篇关于使用 React 和 Webpack 添加 Favicon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!