【发布时间】:2017-01-18 00:52:32
【问题描述】:
我有一个使用 ReactJS 运行的 Webpack,我正在尝试抓取图像并显示它,但出现错误:Uncaught Error: Cannot find module "../media/interiorTest.jpg"
这是我尝试过的:
<div>
<img src={require("../media/interiorTest.jpg")}/>
</div>
目录树是(我正在尝试从home-page.js 获取interiorTest.jpg):
而我的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;
【问题讨论】:
-
../ 会带你进入
components文件夹.. 所以让它../../public/media。或者如果公众真的很公开,你应该使用普通的旧src="/media/interiorTest.jpg" -
@Hardy 尝试了第一个但得到了错误:
Uncaught Error: Cannot find module "../../public/media/interiorTest.jpg",当我尝试没有 src={require()} 而只是 src="" 的第二个建议时,我得到了GET http://localhost:8080/media/interiorTest.jpg 404 (Not Found) -
@Hardy 如果您看到我的最后一条评论,请告诉我
-
您是否忘记粘贴与 jpg 匹配的加载程序定义?
-
@JuhoVepsäläinen 不,webpack.config.js 正是我使用的方式。抱歉,您所说的粘贴与 jog 匹配的加载程序定义是什么意思?
标签: javascript html reactjs webpack react-jsx