【发布时间】:2020-02-06 06:48:33
【问题描述】:
我正在尝试从我的公共目录中获取静态图像,但没有找到。我没有使用 CRA,所以可能是我缺少的一些 Webpack 配置。使用文件加载器模块并导入图像在开发模式下工作,但不适用于我的生产服务器规范
我的项目结构:
\public
\static
\images
image.png
\src
\component
component.js
...
package.json
webpack.common.js
webpack.dev.js
webpack.prod.js
在 component.js 上,我想在 static/images 文件夹中获取 image.jpg,如下所示:
<img src='/static/images/image.png'></img>
但我得到一个 404 未找到。
我的 webpack.commom.js:
const CleanWebPackPlugin = require('clean-webpack-plugin')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
entry: {
main: './src/index.js'
},
output: {
filename: '[name].[hash].js',
path: path.resolve('./dist'),
publicPath: "/"
},
module:{
rules:[
{
test: /\.js$/,
exclude: ['/node_modules'],
use: [{ loader: 'babel-loader'}],
},
{
test: /\.s?(a|c)ss$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader'
},{
loader: 'sass-loader'
}]
},
{
test: /\.(png|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: 'index.html'
}),
new CleanWebPackPlugin(),
],
}
还有开发版:
module.exports = merge(common, {
mode: 'development',
devServer: {
host: 'localhost',
port: 3000,
open: true,
historyApiFallback: true,
publicPath: "/",
}
})
提前谢谢你。
【问题讨论】:
-
几件事:您将“src”设置为“/static/image.png”,但根据您的项目结构,它应该是“/static/images/image.png”。那是错字吗?运行生产构建后,您的“dist/”文件夹是什么样的?它是否包含该图像文件?
-
确实是一个拼写错误。在生产 dist/fold 中,如果我通过加载器 webpack 插件导入,图像就会出现,这对我来说不是一个好的选择。
标签: javascript node.js reactjs webpack ecmascript-6