javascript - React SSR Firebase 应用程序中的图像

标签 javascript reactjs firebase webpack server-side

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

更新:我认为这不仅仅是 Cloud Functions 模拟器的问题,尽管它应该升级到当前的节点版本,但在 Firebase 上部署时我也没有看到图像。我读过一些地方谈论节点要求的图像 Hook ,我只是不知道将它们放在哪里。这是一个很有希望的链接... 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} alt="Image_1" />
    <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 ssrApp = 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'),
);

最佳答案

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

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

关于javascript - React SSR Firebase 应用程序中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744898/

相关文章:

javascript - 如何在页面加载时启动 Phonegap 自定义对话框?

javascript - 在容器内拖动图像,不使用鼠标移动,稍微快一点

javascript - 按解决/执行时间的顺序解决 promise ?

firebase - 如何在 Vapor 中向 Firebase Cloud Messaging API 发送 POST 请求

javascript - 如果使用外部 javascript,模板标记 'url' 不起作用

javascript - 两个图像预加载器

javascript - 如果用户中止连接到服务器(连接时刷新、关闭浏览器等),如何停止执行所有功能(多个异步等)

javascript - React 如何在 componentWillUnmount 中正确移除监听器,为什么我需要在构造函数中绑定(bind)?

java - Android Studio 更新了,现在代码太大了

Android Studio - 程序类型已存在 : com. google.android.gms.location.places.zza