ReactJSのwebpackで画像を読み込むのに適切なローダーがわかりません。
あなたは私に手を差し伸べることができますか? 私はこのエラーを取得します。
Module parse failed: /Users/imac/Desktop/fakeeh/imgs/logo.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
以下はwebpackの設定です。
const path = require('path');
module.exports = {
// the entry file for the bundle
entry: path.join(__dirname, '/client/src/app.jsx'),
// the bundle file we will get in the result
output: {
path: path.join(__dirname, '/client/dist/js'),
filename: 'app.js',
},
module: {
// apply loaders to files that meet given conditions
loaders: [{
test: /\.jsx?$/,
include: path.join(__dirname, '/client/src'),
loader: 'babel-loader',
query: {
presets: ["react", "es2015", "stage-1"]
}
}],
},
// start Webpack in a watch mode, so Webpack will rebuild the bundle on changes
watch: true
};
とても感謝しています!
私もこの問題に遭遇しましたが、回避策を見つけました。
まず、2つのローダー(ファイルローダーとURLローダー)をインストールする必要があります。 例 $ npm install --save file-loader url-loader (ファイルローダーとurlローダーの2つをインストールします。
cssに対応させたい場合。スタイルローダーを必ずインストールしてください。 例 $ npm install --save style-loader css-loader とします。
次に、webpack の設定を更新します。以下のサンプル設定を参照してください。参考になれば幸いです。
module: {
loaders: [{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000' }]
},
file-loader]1を使用することができます。まずnpmを使ってインストールし、webpackの設定を以下のように編集する必要があります。
module: {
// apply loaders to files that meet given conditions
loaders: [{
test: /\.jsx?$/,
include: path.join(__dirname, '/client/src'),
loader: 'babel-loader',
query: {
presets: ["react", "es2015", "stage-1"]
}
},
{
test: /\.(gif|svg|jpg|png)$/,
loader: "file-loader",
}],
},
Webpack 3 では、以下のように url-loader
を使用することができます: Webpack 3 では、以下のように url-loader
を使用することができます。
url-loader
]1 をインストールします。
npm install --save url-loader
次に、Webpackのconfigに
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
}
}
最後に、コード内で
<img src={require('./path/to/image.png')} />