ReactJS + Webpack:为什么没有发现错误:找不到模块“../media/interiorTest.jpg”?

时间:2016-09-09 19:56:18

标签: javascript html reactjs webpack react-jsx

我有一个运行ReactJS的Webpack,我试图抓取一个图像并显示它但收到错误:Uncaught Error: Cannot find module "../media/interiorTest.jpg"

以下是我的尝试:

  <div>
    <img src={require("../media/interiorTest.jpg")}/>
  </div>

目录树是(我正试图从interiorTest.jpg获取home-page.js):

enter image description here

我的webpack.config.js是:

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
  context: __dirname,
  entry: './src/index.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        exclude: /node_modules/,
        test: /\.(js|jsx)$/,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css!sass')
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  },
  plugins: [
    new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify('production') } }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false },
      output: {comments: false },
      mangle: false,
      sourcemap: false,
      minimize: true,
      mangle: { except: ['$super', '$', 'exports', 'require', '$q', '$ocLazyLoad'] }
    }),
    new ExtractTextPlugin('src/public/stylesheets/app.css', {
      allChunks: true
    })
  ]
};

module.exports = config;

1 个答案:

答案 0 :(得分:1)

通过查看webpack.config.js中的代码和您包含的屏幕截图,您的目录结构如下所示

app/
    src/
         actions/
         components/
         ...
         public/

webpack.config.js中你有这段代码

  devServer: {
    historyApiFallback: true,
    contentBase: './'
  },

contentBase 属性定义了服务器运行时将加载文件的目录,并且由于您已将其设置为'./',这意味着文件/数据将从app目录。

这就是从public目录链接文件的原因,你必须在路径中加入/src/public,例如src="/src/public/folder/where/image/is-located/image.jpg"

在这种情况下

  <div>
    <img src="/src/public/media/interiorTest.jpg" alt="" />
  </div>

注意

  • 通常,代码分为两个文件夹,src用于存储您正在处理的代码,public用于存储已编译的代码和静态资源。我们只需将/public设置为contentBase

    值得花时间对反应和javascript应用程序的目录结构进行一些研究

  • 图片有alt=""的好处,只需输入替代文字,因为它最能描述图片。