使用Webpack的file-loader无法加载图像

5
根据file-loader使用文档,我应该能够像这样加载图片:
test: /\.(png|jpg|gif)$/,
use: [
  {
    loader: 'file-loader',
    options: {}  
  }
]

然后通过:

import img from './file.png';

这是我的webpack.config.js文件:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    module: {
        rules: [
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {}
                    }
                ]
            },
            {
                test: /\.glsl$/,
                loader: 'webpack-glsl-loader'
            },
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.ts$/,
                enforce: 'pre',
                loader: 'tslint-loader',
                options: { failOnHint: true }
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    },
    entry: {
        app: './src/index.ts'
    },
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist'
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Output Manager'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    }
};

这是我创建dev-server的方法:
const app = express();

const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
}));

app.listen(3000, () => {
    console.log('Listening on port 3000!\n');
});

此外,我的 src 结构如下:

src
|-images
| |- image.gif
|
|-app.ts

我正在尝试在app.ts中按以下方式加载图像:

import img from './images/image.gif';

// ...

private loadImage(): void {
    const image = new Image();
    image.src = img;
    image.onload = () => {

    };
}

很不幸我得到了以下错误:

GET http://localhost:8080/undefined 404 (未找到)

在Chrome开发工具的导航器中,我可以看到图像文件位于webpack://./src/images/image.gif下。内容如下:

module.exports = __webpack_public_path__ + "9b626fa0956bfa785b543ef53e895d5e.gif";


//////////////////
// WEBPACK FOOTER
// ./src/images/image.gif
// module id = 109
// module chunks = 0

此外,如果我在调试时悬停在img变量上,我可以看到名为"/9b626fa0956bfa785b543ef53e895d5e.gif"的字符串。但是记录该变量会返回undefined,并且image.onload从未被触发。
如果我在浏览器中调用http://localhost:8080/9b626fa0956bfa785b543ef53e895d5e.gif,我可以看到图像。
有任何想法吗?为什么我无法加载图像,尽管我可以在浏览器中看到它,并且路径字符串似乎已经存在?
编辑#1:
由于我正在使用TypeScript,因此必须声明一个模块以导入.gif文件:
declare module "*.gif" {
  const content: any;
  export default content;
}

我发现了这个Github 问题,其中解决此问题的方法是像这样导入文件:import * as styles from "styles.scss"。因此,我尝试通过以下方式导入:

import * as img from './images/img.gif';

很不幸,这导致了以下问题:

错误 TS2322:类型“typeof "*.gif"”不能赋值给类型“string”。

2个回答

4
我看到这里有两个问题。首先,您应该尝试像这样加载图像文件:import * as img from './images/img.gif';。您还必须在某个地方使用该图像才能实际加载它。仅导入不会触发加载文件。但是简单的console.log(img);应该会触发它。
第二个问题是您收到此异常的原因:

error TS2322:类型' typeof "*.gif"'不可分配给类型 'string'。

您应该尝试将导入文件的实际用法包装起来,例如:
if (typeof img === 'string') {
    console.log(img);
}

这样就不会触发异常。
希望这个能帮到你。

将img的调用包装到if语句中实际上解决了问题,谢谢! - チーズパン

0

这是我的webpack配置的一部分。它可以很好地加载图片。

{
    test: /\.(gif|png|jpe?g)$/i,
    exclude: [/node_modules/],
    loaders: [
        'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack-loader'
    ]
}

你能像这样改变路径吗。注意这里有两个点。import * as img from '../images/img.gif'; - pixlboy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接