需要帮助修复 webpack.config 和 relative/absolute 路径

Need help fixing webpack.config with relative/absolute paths

我正在尝试让我的 webpack.config 处理子文件夹中的图像。 我遇到了麻烦。 我花了最后一天半的时间上网,看了各种解决方案都无济于事。

我的 src 文件是:

/src/images/data/

/src/containers

我的问题是: 我有一条路线:http://localhost:7771/games/O 从 /src/containers 加载 在该页面上,我正在尝试加载 /src/images/data/NotFound.png

如果我调用图像使用: <img src="../images/data/NotFound.png"/> 然后图像显示没有任何问题。

但是,如果我将路径更改为 <img src={require("../images/data/NotFound.png")}/>,则图像不会显示。 当我使用 Chrome 开发人员工具检查图像时,我看到该元素显示为: <img src="images/data/NotFound.png"> 如果我将鼠标悬停在 src link 上,我会看到:http://localhost:7771/games/images/data/NotFound.png 但是如果我尝试打开那个 link,图像不会加载。

如果我导航到 http://localhost:7771/images/data/NotFound.png,则会加载图像。

我尝试使用别名进行解析并将图像更改为 <img src={require("~/data/NotFound.png")}> 但结果是一样的,图像无法加载。

这就是为什么我认为我的 webpack.config 搞砸了,我需要一些帮助来找出问题所在,以便我的图片可以显示。

var webpack = require('webpack');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CircularDependencyPlugin = require('circular-dependency-plugin');
var BUILD_DIR =  path.resolve(__dirname,'htmlhot');
var APP_DIR = path.resolve(__dirname, 'src');
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});

var config = {
  context: path.join(__dirname, "src"),
    devtool: 'source-map',
  entry: [
      //'webpack/hot/dev-server',
    // reload controls falling back to page refresh if hot reload fails (  rare ).
    // change to false to debug hot reloading, so you can see the errors before it refreshes the page.
     'webpack-hot-middleware/client?reload=true',
    //  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
      APP_DIR + '/index.js'
      ],

  output: {
    path: path.join(__dirname, "src"),
    filename: 'bundle-hot.js'
  },
  resolve: {
    modules: [
        path.join(__dirname, 'src/'),
        'node_modules/'
    ],
    alias: {
        '~':  APP_DIR + '/images/'
    }
  },
  watch: true,
  watchOptions: {
    poll: true,
    aggregateTimeout: 300,
    number: 1000
  },
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        exclude: /node_modules/,
        loaders: ['react-hot-loader', 'babel-loader?' + JSON.stringify({
        cacheDirectory: true,
        plugins: [
            'transform-runtime',
            'react-html-attrs',
            'transform-class-properties',
            'transform-decorators-legacy'
        ],
        presets: ['es2015', 'react', 'stage-2']
        })]
      },
      // CSS
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject <style> tags.
      // In production, we use a plugin to extract that CSS to a file, but
      // in development "style" loader enables hot editing of CSS.
      {
        test: /\.css$/,
        include: path.join(__dirname, 'src/style'),
        loader: 'style-loader!css-loader'
      },
      // "file" loader makes sure those assets get served by WebpackDevServer.
      // When you `import` an asset, you get its (virtual) filename.
      // In production, they would get copied to the `build` folder.
      {
        test: /\.(ico|jpg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        exclude: /\/favicon.ico$/,
        loader: 'file-loader',
        query: {
            name: '[path][name].[ext]'
        }
      },
      {
        test: /\.(ico)(\?.*)?$/,
        exclude: /node_modules/,
        loader: 'file-loader',
        query: {
            name: '.images/[name].[ext]'
        }
      }
    ]
  },

    // use EnableCircularDependencyPlugin=true|false to check the option
    plugins: (function() {
        var plugins = [
            new CopyWebpackPlugin([
                { from: APP_DIR + '/index.html', to: BUILD_DIR + '/index.html' },
                { from: APP_DIR + '/images/', to: BUILD_DIR + '/images/' }
            ]),
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoEmitOnErrorsPlugin(),
            new webpack.DefinePlugin({
                __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
            })
        ];

        // HERE IS OPTION CONDITION
        // edit .env file change to EnableCircularDependencyPlugin=false will bypass it
        if (process.env.EnableCircularDependencyPlugin=="true") {
            plugins.push(new CircularDependencyPlugin({
                // exclude detection of files based on a RegExp
                exclude: /a\.js|node_modules/,
                // add errors to webpack instead of warnings
                failOnError: true
            }));
        }

        return plugins;
    })(),
    node: {
        net: 'empty',
        dns: 'empty'
    }
};

module.exports = config;

file-loader 尊重 output.publicPath,因为你没有设置一个,它使用相对于 output.path 的路径,并且在使用不同的路线时不起作用。要修复它,只需将 public 路径设置为 /:

output: {
  path: path.join(__dirname, "src"),
  filename: 'bundle-hot.js',
  publicPath: '/'
},
如果您不想设置 output.publicPath

file-loader 也有一个选项 publicPath,因为它也会影响其他加载程序,但这通常是您想要的并且是因此推荐。有了这个你会得到:

<img src="/images/data/NotFound.png">

您也不需要复制 images 目录,因为 file-loader 会复制您导入的图像。事实上,它使用 URL 复制文件。所以你应该从 CopyWebpackPlugin 中删除它,除非你有没有被 webpack 处理的图像。