Webpack URL加载器/文件加载器:无法加载图像(意外字符)

时间:2019-11-08 01:20:28

标签: reactjs image webpack webpack-file-loader urlloader

我正在尝试在我的网站标题上加载个人资料图片,但是在使Webpack合作方面遇到困难。我尝试使用url-loader和file-loader都没有成功。

这是我从nodemon收到的错误消息:

/local/path/project/node_modules/babel-core/lib/transformation/file/index.js:558
      throw err;
      ^

SyntaxError: /local/path/project/public/images/ProfilePic_100px.jpg: Unexpected character '�' (1:0)
> 1 | ����

[nodemon] app crashed - waiting for file changes before starting...

我的项目目录:

enter image description here

我的 Header.js:

import React from 'react';
import PropTypes from 'prop-types';
import ProfilePic from '../../../public/images/ProfilePic_100px.jpg';

class Header extends React.Component {

    render() {
        return (
                <!-- Stuff here -->
                <div className="Header-userCol">
                    <div className="header-userImage">
                        <img src={ProfilePic} alt={"userPic"} />
                    </div>
                    <div className="header-userName">Daniel Way</div>
                </div>

            </header>
        );
    }
}

Header.propTypes = {
    fetchHomePage: PropTypes.func.isRequired,
    fetchProjectsPage: PropTypes.func.isRequired,
    fetchIdeasPage: PropTypes.func.isRequired
}

export default Header;

我的 Webpack.config:

var webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/public',
    filename: 'bundle.js'
  },
  node: {
      fs: 'empty'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.mp3$\.m4a$\.aiff$\.wav$\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)$/,
        loader: 'url-loader'
      },
      {
          test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
          use: [
            {
              loader: "file-loader",
              options: {
                outputPath: './public/images',
                name: "[name].[ext]",
              },
            },
          ]
      },
      {
          test: /\.css$/,
          use: ["style-loader", "css-loader"]
      },
      {
          test: /\.scss$/,
          use: ["style-loader", "'css-loader?modules=true&camelCase=true'", "sass-loader"]
      },
      {
        test: require.resolve("wavesurfer.js"),
        resourceQuery: '/inline/',
        use: "expose-loader"
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({
        WaveSurfer: 'wavesurfer.js'
    }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ],
  resolve: {
      alias: {
          wavesurfer: require.resolve('wavesurfer.js')
      }
  }
};

请注意,从index.js(src目录中的我的入口文件)导入图像没有问题,但是无法从加载到App本身的组件中进行操作。我绝不是webpack向导,因此欢迎所有帮助。谢谢

0 个答案:

没有答案