图片加载到外部库中,如何用 webpack 加载? [英] Images are loaded in external library, how to load them with webpack?
问题描述
首先,我需要说我对 Webpack 的基础知识知之甚少,这可能是我找不到解决方案的原因.
first and foremost I need to say that I know little of fundamentals of Webpack, and this is probably why I can't find a solution.
所以我知道为了加载图像,我需要一个路径而不是将其作为字符串输入require('path/to/image')
So I know in order to load images I need to require a path instead of just typing it as a string require('path/to/image')
然后我得到了一个外部库,我需要在其中传递一个 path
属性,其中放置了多个图像.它似乎不起作用,那么如何将它们加载到我的网站中?
Then I got an external library where I need to pass a path
property, where lay multiple images. It doesn't seem to work, so how can I load them into my website?
<CountrySelect
multi={false}
flagImagePath="../../../public/flags/" //folder with multiple images
/>
Webpack 配置:
Webpack config:
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 解决了这个问题.
I solved the problem by using 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 中:
and in CountrySelect:
flagImagePath="/flags/"
这样在生产时,静态目录是dist
,标志是从dist
目录派生的.
So that in the time of production, where static directory is dist
, flags are derived from dist
directory.
这篇关于图片加载到外部库中,如何用 webpack 加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!