我在尝试将图像导入项目时遇到此问题时遇到此错误:模块解析失败:C:\ Users \ Angelo \ OptaService \ OptaService \ images \ ImageTest.png意外字符'� ' (1:0) 您可能需要适当的加载程序来处理此文件类型。
这是我的webpack配置:
module: {
rules: [
{test: /\.(js)$/, use: 'babel-loader', exclude: /node_modules/},
{test: /\.css$/, use: ['style-loader', 'css-loader']},
],
loaders: [ {
test: /\.js|.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
}, {
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
} ]
},
我已经在npm安装了image-webpack-loader和file-loader。 我还要在组件中导入图像,如下所示:
import image from './../../images/ImageTest.png';
...
<img className="img-fluid" src={image} alt="OptaService Logo"/>
提前致谢!
答案 0 :(得分:0)
这是我设置您的webpack配置的方式,您正在混合加载器和规则,您可以查看docs以进一步调查如何正确设置配置。
module: {
rules: [
{
test: /\.js|.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
]
},
答案 1 :(得分:0)
最好设置Webpack配置文件以在生产和开发中分别支持不同的文件类型,并最大程度地支持所有文件。为此,我建议在项目的根目录中为Webpack配置添加3个文件。
webpack.common.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
app: './src/App.js'
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: 'style-loader',
options: {
sourceMap: true
}
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]--[hash:base64:5]',
sourceMap: true
}
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(png|svg|jpg|gif|pdf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
}
]
}
};
webpack.prod.js
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
});
webpack.dev.js
const path = require("path");
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devtool: 'source-map',
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
port: 8181,
open: 'google chrome',
historyApiFallback: true
}
});
使用这3个配置文件,您在项目的根目录中需要'dist'和'src'目录。