代码之家  ›  专栏  ›  技术社区  ›  Héctor León

React的网页3图像src问题(html加载程序和transform React jsx img导入)

  •  1
  • Héctor León  · 技术社区  · 7 年前

    U P D A T E D 修复了存储库中的代码


    我正在尝试设置React图像的网页包配置 避免丑陋 var myImage = require('./imagePath/image.jpg');

    (背景图像,即) ,但如果我尝试在索引中添加图像。html或在react组件中,它们不会生成。

    文件加载器 , html加载程序 transform react jsx img导入

    我创建了 this repository ,使用示例案例。

    您可以克隆它,只需通过 npm install yarn install

    在过去的两天里,我一直在努力解决这个问题,所以如果有任何帮助,我将不胜感激。

    const autoprefixer      = require('autoprefixer'),
          DashboardPlugin   = require('webpack-dashboard/plugin'),
          ExtractTextPlugin = require('extract-text-webpack-plugin'),
          HtmlPlugin        = require('html-webpack-plugin'),
          path              = require('path'),
          webpack           = require('webpack');
    
    const isProd = process.env.NODE_ENV === 'production';
    
    
    
    //////////////////////// FILEPATH ///////////////////////
    /////////////////////////////////////////////////////////
    
    const buildFolder = 'dist';
    const PATHS = {
      src       : path.resolve(__dirname, 'src'),
      build     : path.resolve(__dirname, buildFolder),
      appJS     : path.resolve(__dirname, 'src/app.js'),
      indexHTML : path.resolve(__dirname, 'src/index.html')
    }
    
    
    
    //////////////////////// PLUGINS ////////////////////////
    /////////////////////////////////////////////////////////
    const HtmlPluginOptions = {
      template: PATHS.indexHTML,
      minify: {
        collapseWhitespace: true
      },
      hash: true
    };
    
    const ExtractTextPluginOptions = {
      filename: '[name].bundle.css',
      disable: !isProd,
      allChunks: true,
      ignoreOrder: false
    }
    
    const devServerOptions = {
      contentBase: PATHS.build,
      compress: true,
      port: 6969,
      stats: 'errors-only',
      open: true,
      hot: true,
      openPage: ''
    };
    
    const pluginsDev = [
      new DashboardPlugin(),
      autoprefixer,
      new HtmlPlugin(HtmlPluginOptions),
      new ExtractTextPlugin(ExtractTextPluginOptions),
      new webpack.HotModuleReplacementPlugin()
    ];
    
    const pluginsProd = [
      require('autoprefixer'),
      new HtmlPlugin(HtmlPluginOptions),
      new ExtractTextPlugin(ExtractTextPluginOptions)
    ];
    
    var pluginsList = isProd ? pluginsProd : pluginsDev;
    
    
    
    //////////////////////// LOADERS ////////////////////////
    /////////////////////////////////////////////////////////
    const postcss = {
      loader: 'postcss-loader',
      options: {
        sourceMap: 'inline',
        plugins() {
          return [autoprefixer({ browsers: 'last 3 versions' })];
        }
      }
    };
    
    const stylesDev  = ['style-loader', 'css-loader?sourceMap', postcss, 'sass-loader?sourceMap'];
    const stylesProd = ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: ['css-loader', postcss, 'sass-loader'],
      publicPath: buildFolder
    });
    
    const styles = {
      test: /\.scss$/,
      use: isProd ? stylesProd : stylesDev
    };
    
    const javascript = {
      test: /\.(js|jsx)$/,
      use: 'babel-loader',
      exclude: /node_modules/
    }
    
    const images = {
      test: /\.(jpe?g|svg|png|gif)$/i,
      use: [
        'file-loader?name=assets/img/[name].[ext]'
      ]
    }
    
    const html = {
      test: /\.(html)$/,
      use: {
        loader: 'html-loader',
        options: {
          attrs: ['img:src', 'link:href']
        }
      }
    }
    
    
    
    //////////////////////// WEBPACK ////////////////////////
    /////////////////////////////////////////////////////////
    const webpackConfig = {
      entry: {
        app: PATHS.appJS
      },
      output:  {
        path: PATHS.build,
        filename: '[name].bundle.js'
      },
      module: {
        rules: [javascript, styles, images, html]
      },
      devServer: devServerOptions,
      plugins: pluginsList
    }
    
    module.exports = webpackConfig;
    

    /src/index.html <img> 标签 而且 与其他人归档 <img> 标签

    此存储库

    2 回复  |  直到 7 年前
        1
  •  2
  •   Michael Jungo    7 年前

    以开头的URL / 不由转换 html-loader 'Root-relative' URLs ). 大多数加载程序遵循这种行为,因为这允许您使用使用服务器上未经webpack处理的文件的现有文件。此外,如果它将URL解释为路径(就像在任何JavaScript模块中一样),那么它将在文件系统的根中查找,而这不是您想要的。

    <img src="./public/assets/img/logo--webpack.svg" alt="Logo Webpack"/>
    

    在React组件中,不能使用 因为您实际上并不是在编写HTML,而是在编写JSX,JSX是一种语法糖,它将被转换为函数调用。有关详细信息,请参阅 JSX In Depth .

    src 属性

    import reactLogo from '../public/assets/img/logo--react.svg';
    
    <img src={reactLogo} alt="Logo React"/>
    

    <img> babel-plugin-transform-react-jsx-img-import ,虽然我不知道这是否有效,因为它似乎没有得到维护。

        2
  •  0
  •   Alessander França    7 年前

    我在我的webpack 3配置中用于加载图像的是:

         {
            test: /\.(png|svg|jpg|webp)$/,
            use: {
              loader: 'file-loader',
            },
          },
    

    我的react组件中的代码:

    import logo from '../../img/logo.png';
    
    ...
    
    <img className={style.logo} src={logo} alt="logo" />