如何在localhost上获取Webpack 2 / React App中的静态图像路径?

时间:2017-06-02 16:10:21

标签: javascript reactjs webpack localhost webpack-2

预期

图像和CSS路径在本地加载正常,没有错误

结果

样式和图像上的404错误

enter image description here

我的样式运行正常,但是有一个丢失的错误,同时应用程序找不到static/imgs文件夹

enter image description here

我的文件夹结构

enter image description here

登录组件

图片路径:

render() {
    return (
        <div className="app-bg">
            <section id="auth-section">
                <header>
                    <img src="static/imgs/logo.png"/>
                    <h1>Login to the Manage app</h1>
                </header>

Webpack配置

const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");

module.exports = {
  context: path.resolve(__dirname, "src"),
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      // title: "Manage 2.0",
      // hash: true,
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static" }])
  ]
};

的src / index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import css from './manage2.scss'
const element = document.getElementById('manage2');
ReactDOM.render(<App />, element);

我尝试将publicPath: "/"更改为""./无效...

1 个答案:

答案 0 :(得分:0)

我需要将 publicPath 更改为以下内容:

output: {
  path: dist,
  filename: "manage2.bundle.js",
  publicPath: '/static/',
},