首先,我需要说的是,我对Webpack的基础知识了解甚少,这可能就是为什么我找不到解决方案的原因。
所以我知道要加载图像,我需要一个路径,而不仅仅是将其键入为字符串require('path/to/image')
然后,我有了一个外部库,我需要在其中传递一个path
属性,其中放置了多个图像。它似乎不起作用,那么如何将它们加载到我的网站中?
<CountrySelect
multi={false}
flagImagePath="../../../public/flags/" //folder with multiple images
/>
Webpack配置:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const outputDirectory = 'dist';
module.exports = {
entry: './src/client/index.js',
output: {
path: path.join(__dirname, outputDirectory),
filename: 'bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|jpg|jpeg)$/,
loader: 'url-loader?limit=100000'
}
]
},
devServer: {
historyApiFallback: true,
port: 3000,
open: true,
proxy: {
'/api': 'http://localhost:8080'
}
},
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.ico'
})
]
};
答案 0 :(得分:1)
我通过使用CopyWebpackPlugin解决了这个问题。
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.png'
}),
new CopyWebpackPlugin([{ from: './public/flags', to: 'flags', toType: 'dir'
}]),
]
并在CountrySelect中:
flagImagePath="/flags/"
因此,在生产时,静态目录为dist
,标志是从dist
目录派生的。
答案 1 :(得分:0)
image-webpack-loader
-自动缩小/压缩较大的图像。
url-loader
-如果图像尺寸较小,它将作为bundle.js的一部分包含在内,否则将创建单独的目录并将图像放置在其中。
npm install --save-dev image-webpack-loader url-loader file-loader
webpack.config.js
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: 'build/' //This is important to load your images.
},
module: {
rules: [
{
test: /\.js$/,
use: [
{ loader: 'babel-loader' },
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'url-loader',
options: { limit: 40000 } //if image of size lessthan 40kb include it in bundle.js
},
'image-webpack-loader'
]
}
]
}
}
示例代码。
import big from '../images/big.jpg';
import small from '../images/small.png';
const image = document.createElement('img');
image.src = small;
document.body.appendChild(image);
const bigimage = document.createElement('img');
bigimage.src = big;
document.body.appendChild(bigimage);
您可以从Handling Images with Webpack了解有关webpack的更多信息。