React s-s-r Firebase 应用程序中的图像

Posted

技术标签:

【中文标题】React s-s-r Firebase 应用程序中的图像【英文标题】:Images in a React s-s-r Firebase App 【发布时间】:2018-05-24 12:03:08 【问题描述】:

我对 React 还很陌生,我正在构建一个通用应用程序。我最近关注了 Firebase 在 YouTube 上发布的教程。它按预期工作。然后我编写了自己的代码,这样我就可以开始自己的应用程序了。当涉及到 firebase 和我的图像文件时,我遇到了问题。我怀疑这是 Webpack 或 Node 的问题。

更新:我不认为这只是 Cloud Functions 模拟器的问题,虽然它应该升级到当前节点版本,但在 Firebase 上部署时我也看不到图像。我读过一些关于 node require 的图像钩子的地方,我只是不知道把它们放在哪里。这是一个有希望的链接...https://www.npmjs.com/package/images-require-hook

来自终端的错误

firebase serve --only hosting,functions

=== Serving from '/Users/danielrehbein/Sites/express-react'...

i  functions: Preparing to emulate functions.
Warning: You're using Node.js v8.3.0 but Google Cloud Functions only 
supports v6.11.5.
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000

⚠  functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
⚠  functions: Error from emulator. FirebaseError: Error parsing triggers: Cannot find module '../images/image1.jpg'

Try running "npm install" in your functions directory before deploying.

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');


require('asset-require-hook')(
  extensions: ['.jpg', '.png', '.gif'],
);

module.exports = [

  devtool: 'source-map',
  entry: ['./src/index.js',
    './res/scss/main.scss',
  ],
  module: 
    loaders: [
      // handles the react components and all other JS and bundles it to es2015 standards
      
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      ,
      // Handles any errant .jsx files that made their way into the project
      
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      ,
      // handles scss styling and writes DRY css.
      
        test: /\.scss$/,
        use: ExtractTextPlugin.extract(
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader', 'postcss-loader'],
        ),
      ,
      // handles any image files
      
        test: /\.(png|jpg|gif)$/,
        use: [
          loader: 'file-loader',
          options: 
            outputPath: 'public/images/',
            publicPath: 'public/images/',
          ,
        ],
      ,
    ],
  ,
  output: 
    filename: 'public/bundle.js',
    path: __dirname,
  ,
  plugins: [
    new webpack.DefinePlugin(
      'process.env': 
        NODE_ENV: JSON.stringify('production'),
      ,
    ),
    new UglifyJSPlugin(
      sourceMap: true,
    ),
    new ExtractTextPlugin('public/styles.css'),
    new OptimizeCssAssetsPlugin(),
  ],
];

带有图像文件的组件。

import React from 'react';

const image1 = require('../images/image1.jpg');

const Home = () => (
  <div className="home">
    <img src=image1  />
    <h1>Welcome</h1>
  </div>
);

export default Home;

index.js

import * as React from 'react';
import ReactDOMServer from 'react-dom/server';
import  StaticRouter  from 'react-router';
import express from 'express';
import * as fs from 'fs';
import * as functions from 'firebase-functions';
import path from 'path';

// import main react app below.

import App from './src/App';

const resolvedIndex = path.join(__dirname, 'index.template.html');

const index = fs.readFileSync((resolvedIndex), 'utf-8');

const context = ;

const app = express();

app.get('**', (req, res) => 

  const html = ReactDOMServer.renderToString(
    <StaticRouter location=req.url context=context >
      <App />
    </StaticRouter>);

  const finalHtml = index.replace('<!-- ::APP:: -->', html);
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200');
  res.send(finalHtml);
);

export let s-s-rApp = functions.https.onRequest(app);

src/App.js

// import dependancies below

import React from 'react';
import  Route, Switch  from 'react-router-dom';

// Import Page components

import Header from './components/header';
import NavMenu from './components/NavMenu';
import Footer from './components/footer';

// Import Pages

import Home from './components/home';
import About from './components/About';
import Contact from './components/contact';
import Oops from './components/oops';


const App = () => (
  <div>
    <Header />
    <NavMenu />
    <Switch>
      <Route exact path="/" component=Home />
      <Route exact path="/about" component=About />
      <Route exact path="/contact" component=Contact />
      <Route path="*" component=Oops />
    </Switch>
    <Footer />

  </div>
);

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import  BrowserRouter  from 'react-router-dom';

import App from './App';

ReactDOM.render(
  (
    <BrowserRouter>
      <App />
    </BrowserRouter>
  ), document.getElementById('root'),
);

【问题讨论】:

【参考方案1】:

也许这是一个模拟器问题。认为您已升级节点并尝试运行该应用程序,但现在它无法运行。

尝试使用 npm 卸载 Google Cloud Functions。您可以在此处阅读有关模拟器的信息:https://github.com/GoogleCloudPlatform/cloud-functions-emulator/wiki

【讨论】:

感谢您的回复,虽然我不确定在这种情况下这完全是我的问题,因为当我注释掉需要图像并将图像放置在组件中的行时,我没有收到错误。 我怀疑我需要某种图像需要钩子,但我不知道如何实现。【参考方案2】:

由于您在 web pack 配置中为图像资源指定了公共路径,因此您可能无法直接访问它或以这种方式导入 React 组件中的 require('../images/image1.jpg'); 组件中,而不是 @987654324 @。

基于您的配置

use: [
     loader: 'file-loader',
     options: 
       outputPath: 'public/images/',
       publicPath: 'public/images/',
     ,
],

公共路径

publicPath 配置选项在各种情况下都非常有用。它允许您为应用程序中的所有资产指定基本路径。

如果您想像 require('../images/image1.jpg'); 那样导入它并且在您的 css 中像这样 background-image: url(/images/image1.jpg) 那么您可以将您的图像配置重构为这样


  test: /\.(jpe?g|gif|png|svg)$/,
  loader: 'file-loader?name=images/[name].[ext]'
,

【讨论】:

以上是关于React s-s-r Firebase 应用程序中的图像的主要内容,如果未能解决你的问题,请参考以下文章

使用 firebase-functions 部署基于反应的 s-s-r 应用程序时出错

在 Firebase 上部署 Angular 8 Universal (s-s-r) 应用程序

如何通过云功能将 Nuxt s-s-r 应用部署到 Firebase?

带有 Firebase 的 Nuxt.js s-s-r - ReferenceError:未定义导航器

使用 Firebase 云功能为带有 i18n 的 Angular 10 s-s-r 通用应用程序提供服务

如何将 Firebase Firestore 数据添加到 s-s-r Nuxt Apps Vuex Store