reactjs - 使用 React、Webpack 和 Express 无法在浏览器中加载图像

标签 reactjs express webpack urlloader

我正在使用 React 构建一个网站。在我实现 Express 之前,它工作得很好。实现express后,我无法加载某些资源,尤其是浏览器中的图像。图像路径正确,但图像未在浏览器中显示。

webpack.config.js是:

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  devtool: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.join(__dirname, 'app/index.js')
  ],
  output: {
    path: path.join(__dirname, '/dist/'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [
    new ExtractTextPlugin('/bundle.css', { allChunks: true }),
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ],
  resolve: {
    extensions: ['', '.scss', '.css', '.js', '.json'],
    modulesDirectories: [
      'node_modules',
      path.resolve(__dirname, './node_modules')
    ]
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        "presets": ["react", "es2015", "stage-0", "react-hmre"]
      }
    }, {
      test: /\.json?$/,
      loader: 'json'
    }, {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass')
    }, {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
    },{
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: "url-loader?limit=10000"
    },{
        test: /\.less$/, loader: "style-loader!css-loader!less-loader"
    },{
        test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/, 
        loader: "file-loader"
    }]
  }
};

server.js文件内容如下:

const path = require("path");  
const express = require("express");  
const webpack = require("webpack");  
const webpackDevMiddleware = require("webpack-dev-middleware");  
const webpackHotMiddleware = require("webpack-hot-middleware");  
const config = require("./webpack.config.js");

const app           = express(),  
      DIST_DIR      = path.join(__dirname, "dist"),
      HTML_FILE     = path.join(DIST_DIR, "index.html"),
      isDevelopment = process.env.NODE_ENV !== "production",
      DEFAULT_PORT  = 3000,
      compiler      = webpack(config);

app.set("port", process.env.PORT || DEFAULT_PORT);

if (isDevelopment) {  
    app.use(webpackDevMiddleware(compiler, {
        publicPath: config.output.publicPath
    }));

    app.use(webpackHotMiddleware(compiler));

    app.get("*", (req, res, next) => {
        compiler.outputFileSystem.readFile(HTML_FILE, (err, result) => {
            if (err) {
                return next(err);
            }
            res.set('content-type', 'text/html');
            res.send(result);
            res.end();
        });
    });
}

else {  
    app.use(express.static(DIST_DIR));

    app.get("*", (req, res) => res.sendFile(HTML_FILE));
}

app.listen(app.get("port"));

package.json如下:

"main": "server.js",
  "script": {
    "start": "babel-node server-es6.js",
    "build:server": "babel server-es6.js --out-file server.js",
    "build:client": "webpack -p --config webpack.config.js --progress"
  },

网站正在加载,但某些 css 未加载。控制台抛出错误:

GET http://bundle.css/ net::ERR_NAME_NOT_RESOLVED

图像路径正确为 http://localhost:3000/img/img1.png但它没有显示在浏览器中。我认为问题出在 webpack 公共(public)路径上。

当我使用<img src={require('/images/image-name.png')} />时,其工作正常。但我不想这样做,因为它的代码库非常繁重,而且我认为这不是一个很好的解决方案。

我得到了 webpack-express-boilerplate 的帮助.

在 Chrome 网络工具中,图像类型为 text/html .

最佳答案

如果您的文件路径是静态的,您可以导入一次文件,然后将其作为 src 提供

import image from '/path/to/images/image-name.png';
...
<img src={image} />

关于reactjs - 使用 React、Webpack 和 Express 无法在浏览器中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45229438/

相关文章:

javascript - map 未呈现内容

javascript - 如何在 React Redux 中渲染 JSON 数据数组

javascript - 如何运行 "npm start"永远运行

javascript - 如何在React中同步操作或者说如何让react js代码逐行运行?

javascript - 使用 browserify 和 bootstrap 引发错误来 react js

javascript - 使用express.bodyParser()和passport.js

javascript - 尝试使用 Express 将数据插入 MySql 数据库时出错

node.js - Winston/Node.js 如何仅为特定路线添加运输?

javascript - 将 Stylelint 与 Vue.js 集成

webpack - 无服务器框架功能的 AWS Lambda 文件系统路径?