Ich versuche, ein Favicon zu einer React-basierten Website hinzuzufügen, die ich mit Webpack erstellt habe. Es war ein absoluter Albtraum, ein Favicon hinzuzufügen, und ich habe viele Lösungen ohne Erfolg ausprobiert. Die neueste, mir empfohlene Lösung heißt 'favicons-webpack-plugin'. Sie finden sie hier: https://github.com/jantimon/favicons-webpack-plugin .
Wenn mir jemand sagen kann, was ich falsch mache, wäre Ihre Hilfe sehr dankbar.
Ich erhalte die folgende Fehlermeldung, wenn ich 'npm run start' starte
Dies ist meine Verzeichnisstruktur:
Dies ist meine webpack.config.js-Datei:
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
}
})
]
});
}
Dies ist meine server.js-Datei:
/* 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()}`));
Für zukünftige Googler: Sie können auch copy-webpack-plugin verwenden und dies zur Produktions-Konfiguration von webpack hinzufügen:
plugins: [
new CopyWebpackPlugin([
// relative path is from src
{ from: './static/favicon.ico' }, // <- your path to favicon
])
]
Browser suchen Ihr Favicon in /favicon.ico
, dort muss es sein. Sie können noch einmal überprüfen, ob Sie sie an der richtigen Stelle positioniert haben, indem Sie zu [address:port]/favicon.ico
navigieren und sehen, ob Ihr Symbol angezeigt wird.
Im Dev-Modus verwenden Sie historyApiFallback. Daher müssen Sie das Webpack so konfigurieren, dass das Symbol für diese Route explizit zurückgegeben wird:
historyApiFallback: {
index: '[path/to/index]',
rewrites: [
// shows favicon
{ from: /favicon.ico/, to: '[path/to/favicon]' }
]
}
Versuchen Sie in Ihrer server.js
-Datei die URL explizit neu zu schreiben:
app.configure(function() {
app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});
(oder Ihr Setup zieht es vor, URLs neu zu schreiben)
Ich empfehle, eine echte .ico
-Datei zu generieren, anstatt einen .png
zu verwenden, da ich festgestellt habe, dass dies bei Browsern zuverlässiger ist.
Das Hinzufügen Ihres Favicons in den öffentlichen Ordner sollte dies tun. Vergewissern Sie sich, dass das Favicon "favicon.ico" heißt.
Hier ist alles was Sie brauchen:
new HtmlWebpackPlugin({
favicon: "./src/favicon.gif"
})
Das ist definitiv nachdem Sie "favicon.gif" zum Ordner "src" hinzugefügt haben.
Dadurch wird das Symbol in Ihren Build-Ordner übertragen und in Ihr Tag aufgenommen, z. B. <link rel="shortcut icon" href="favicon.gif">
. Dies ist sicherer als nur das Importieren mit copyWebpackPLugin
.
Eine andere Alternative ist
npm install react-favicon
Und in Ihrer Bewerbung würden Sie einfach Folgendes tun:
import Favicon from 'react-favicon';
//other codes
ReactDOM.render(
<div>
<Favicon url="/path/to/favicon.ico"/>
// do other stuff here
</div>
, document.querySelector('.react'));
Es ist dasselbe wie das Hinzufügen anderer externer Skripte oder Stylesheets. Alles, was Sie tun müssen, ist, den korrekten Pfad und rel und type anzugeben.
Hinweis: Wenn sich mein Favicon-Bild im Ordner Anlagenordner befand, war es das Favicon wurde nicht angezeigt. Also habe ich kopierte das Bild in den gleichen Ordner wie in meiner index.html und es funktionierte einwandfrei.
<head>
<link rel="shortcut icon" type="image/png/ico" href="/favicon.png" />
<title>SITE NAME</title>
</head>
Es hat für mich funktioniert. Ich hoffe es funktioniert auch für dich.
So habe ich es gemacht.
in public/index.html
Fügt generierte Favicon-Links hinzu
in src/App.js
import '/path/to/favicon.ico';
in webpack.js
neues HTMLWebpackPlugin ({ favicon: '/path/to/favicon.ico' ,}),
Hinweis. Ich verwende historyApiFallback im dev-Modus, aber ich brauchte kein zusätzliches Setup, um das Favicon auf die Serverseite zu bringen.
Ich werde einfache Schritte zum Hinzufügen von Favicon geben :-)
logo.png
logo.png
in favicon.ico
ändern
Hinweis: Beim Speichern ist es
favicon.ico
. Stellen Sie sicher, dass es nichtfavicon.ico.png
ist.
Das Update kann einige Zeit dauern
Ändern Sie die Symbolgröße in manifest.json, wenn Sie nicht warten können
In meinem Fall - ich verwende Visual Studio (Professional 2017) im Debug-Modus mit Webpack 2.4.1 - musste das favicon.ico
in das Stammverzeichnis des Projekts, genau dort, wo sich der Ordner src
befindet, und nicht in einem Ordner public
, obwohl laut https: // create-react-app .dev/docs/using-the-public-folder Letzteres sollte der offizielle Speicherort sein.
Verwenden Sie dazu den file-loader :
{
test: /\.(svg|png|gif|jpg|ico)$/,
include: path.resolve(__dirname, path),
use: {
loader: 'file-loader',
options: {
context: 'src/assets',
name: 'root[path][name].[ext]'
}
}
}