reactjs - 图片在外部库中加载,如何使用 webpack 加载它们?
问题描述
首先我要说的是我对 Webpack 的基础知识知之甚少,这可能就是我找不到解决方案的原因。
所以我知道为了加载图像我需要一个路径而不是仅仅将它作为字符串输入require('path/to/image')
然后我得到了一个外部库,我需要在其中传递一个path
属性,其中放置多个图像。它似乎不起作用,那么如何将它们加载到我的网站中?
<CountrySelect
multi={false}
flagImagePath="../../../public/flags/" //folder with multiple images
/>
网络包配置:
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'
})
]
};
解决方案
我通过使用 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
目录派生的。
推荐阅读
- python - 在 Python 中求解递归微分方程组
- opencascade - 我已经使用 AIS_LengthDimension 创建了维度注释,现在我想移动创建的注释
- python - OperationalError 1241:操作数应包含 1 列
- oauth-2.0 - keycloak javascript 适配器可以安全使用吗?
- python - 如何从 pip 获取包的 github URL?
- python - 自定义张量流模型中文本标记中的不平衡标签
- javascript - HTML CSS 模态:固定位置不起作用
- python - 如何计算discord.py中两个时间戳_a和_b之间的差异?
- excel - ComboBox 的 RowSouce 属性中的条件
- excel - 格式条件中的多个 xlBetween 运算符