使用React和Webpack添加Favicon [英] Add Favicon with React and Webpack
问题描述
我正在尝试将一个favicon添加到我使用webpack创建的基于React的网站上。添加一个favicon是一个彻头彻尾的噩梦,我尝试了许多解决方案无济于事。推荐给我的最新解决方案名为'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}的数组`
configuration = {
appName:null,//你的应用程序的名字。 `string`
appDescription:null,//您的应用程序的描述。 `string`
developerName:null,//您的(或您的开发人员)名称。 `string`
developerURL:null,//您的(或您的开发人员)URL。 `string`
background:#iff,//展平图标的背景颜色。 `string`
path:/,//覆盖默认图标路径的路径。 `string`
url:/,// OpenGraph图像的绝对URL。 `string`
显示:standalone,// Android显示:browser或standalone。 `string`
orientation:portrait,// Android orientation:portrait或landscape。 `string`
版本:1.0,//您的应用程序的版本号。 `number`
logging:false,//将日志打印到控制台? `boolean`
online:false,//使用RealFaviconGenerator创建favicon? `boolean`
图标:{
android:true,//创建Android主屏幕图标。 `boolean`
appleIcon:true,//创建Apple touch图标。 `boolean`
appleStartup:true,//创建Apple启动映像。 `boolean`
coast:true,//创建Opera Coast图标。 `boolean`
favicons:true,//创建常规favicons。 `boolean`
firefox:true,//创建Firefox OS图标。 `boolean`
opengraph:true,//创建Facebook OpenGraph图像。 `boolean`
twitter:true,//创建Twitter摘要卡图片。 `boolean`
windows:true,//创建Windows 8磁贴图标。 `boolean`
yandex:true //创建Yandex浏览器图标。 `boolean`
}
},
callback = function(错误,响应){
if(error){
console.log(error.status); // HTTP错误代码(例如`200`)或`null`
console.log(error.name); //错误名称,例如API错误
console.log(error.message); //错误描述,例如发生了未知错误
}
console.log(response.images); // {name:string,contents:< buffer> }
console.log(response.files); // {name:string,contents:< string> }
console.log(response.html); //字符串数组(html元素)
};
favicons(来源,配置,回调);
const pkg = require('./ package.json');
const PATHS = {
app:path.join(__ dirname,'app'),
build:path.join(__ dirname,'build')
} ;
process.env.BABEL_ENV = TARGET;
const common = {
条目:{
app:PATHS.app
},
//添加resolve.extensions
// ''需要允许没有扩展名的导入
//注意扩展名之前的。,因为没有它们将无法加载
解决:{
extensions:['',' .js','。jsx','。json']
},
输出:{
路径:PATHS.build,
文件名:'bundle.js'
},
模块:{
加载器:[
{
//测试需要一个RegExp!请注意!
test:/\.css$/,
loaders:['style','css'],
// Include接受路径或路径数组
包括:PATHS.app
},
//设置JSX。这也接受了js,这要归功于RegExp
{
test:/\。(js | jsx)$ /,
//启用缓存以提高开发期间的性能
// It默认使用默认的OS目录。如果你需要更多自定义的东西,
//传递一个路径。即:babel?cacheDirectory =< path>
加载器:[
'babel?cacheDirectory,presets [] = es2015'
],
//仅解析app文件如果没有这个,它将通过整个项目。
//除了慢,这可能会导致错误
包括:PATHS.app
}
]
}
};
//默认配置。如果在bpm之外调用
// Webpack,我们将返回此。
if(TARGET ==='start'||!TARGET){
module.exports = merge(common,{
devtool:'eval-source-map',
devServer:{
contentBase:PATHS.build,
//启用历史API回退,因此HTML5 HISTORY API基于
//路由工作。这是一个很好的默认值方便更多
//复杂的设置。
historyApiFallback:true,
hot:true,
inline:true,
progress:true,
//仅显示错误以减少输出量
stats:'仅错误',
//从env解析主机和端口,这样可以轻松自定义
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,{
条目:{
vendor:Object.keys(pkg.dependencies).filter(function(v){
return v!=='alt-utils';
}),
style:PATHS.style
},
输出:{
路径:PATHS.build,
//使用条目名输出
filename:'[name]。 [chunkhash] .js',
chunkFilename:'[chunkhash] .js'
},
模块:{
加载器:[
//在构建期间提取CSS
{
test:/\.css$/,
loader:ExtractTextPlugin.extract('style','css'),
包括:PATHS.app
}
]
},
插件:[
//将提取的CSS输出到文件
new ExtractTextPlugin('[name]。[chunkhash] .css' ),
//提取供应商和清单文件
new webpack.optimize.CommonsChunkP lugin({
names:['vendor','manifest']
}),
//设置DefinePlugin会影响React库的大小!
new webpack.DefinePlugin({
'process.env.NODE_ENV':'production'
}),
new 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');
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 / fabic.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({
favicon:。/ src / favicon.gif
} )
这肯定是在favicon.gif添加到文件夹src之后。
这会将图标转移到您的构建文件夹并将其包含在您的标记中,如此< link rel =快捷图标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屋!