javascript – 添加Favicon与React和Webpack

我正在尝试添加一个图标到我使用webpack的基于React的网站.添加一个图标是一个完全的恶梦,我尝试了许多解决方案无效.已经推荐给我的最新解决方案叫做“favicons-webpack-plugin”,可以在这里找到: https://github.com/jantimon/favicons-webpack-plugin.

如果有人能告诉我我在做错什么,你的协助将不胜感激.

当我运行’npm运行开始’时,我收到以下错误

这是我的目录结构:

这是我的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()}`));

解决方法

浏览器在/favicon.ico中找到您的图标,这就是它需要的地方.您可以通过导航到[地址:端口] /favicon.ico将您的位置定位在正确的位置,看看是否出现图标.

在开发模式下,您正在使用historyApiFallback,因此需要配置webpack才能显式地返回该路由的图标:

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

在您的server.js文件中,尝试显式重写url:

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

(或者您的设置更喜欢重写URL)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)