首页 > 解决方案 > 图片在外部库中加载,如何使用 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'
    })
  ]
};

标签: reactjswebpack

解决方案


我通过使用 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目录派生的。


推荐阅读