React SSR Firebase应用程序中的图像

时间:2017-12-11 00:15:55

标签: javascript reactjs firebase webpack server-side

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

更新:我认为这不仅仅是云功能模拟器的一个问题,虽然它应该用于当前节点版本,但是我在Firebase上部署时也没有看到这些图像。我已经阅读了一些关于节点需要的图像钩子的地方,我只是不知道在哪里放置它们。这是一个有希望的链接...... 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'),
);

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

基于您的配置

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]'
},
相关问题