使用 Webpack 提供静态图像 [英] Serving static images with Webpack

查看:30
本文介绍了使用 Webpack 提供静态图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 webpack 时遇到问题,无法在 webpack 开发服务器上提供静态图像.

I am having trouble with webpack and react serving static images on webpack dev server.

这是我当前的文件夹结构

This is my currenct folder structure

如您所见,我有一个资产文件夹,其中包含我所有的图片这是我的webpack入口和输出配置

As you can see I have a assets folder witch holds all my images This is my webpack entry and output configuration

客户入口是我的反应项目的来源CLIENT_ENTRY: path.join(process.cwd(), 'src/client/index.jsx')

Where client entry is source of my react project CLIENT_ENTRY: path.join(process.cwd(), 'src/client/index.jsx')

现在这是当 webpack 完成它的一部分时我在 BASH 中的输出

Now here is my output in BASH when webpack has done its part

这是我尝试从项目根目录中的资产文件夹加载图像的地方

And here is where I am trying to load images from assets folder in root of the project

预计只有导入工作.

我尝试在 webpack 中像这样更改输出和公共路径路径:path.resolve(__dirname, 'dist'),公共路径:'/',

I have tried to change the output and public path like so in webpack path: path.resolve(__dirname, 'dist'), publicPath: '/',

path: path.resolve(__dirname, 'dist/assets'),publicPath: '/assets/',

path: path.resolve(__dirname, 'dist/assets'), publicPath: '/assets/',

路径:path.resolve(__dirname, 'dist'),publicPath: '/assets',

path: path.resolve(__dirname, 'dist'), publicPath: '/assets',

路径:path.resolve(__dirname, 'dist'),publicPath: '/assets/',

path: path.resolve(__dirname, 'dist'), publicPath: '/assets/',

等等.等等.

如果有人可以帮助我那就太好了

If someone could help me that would be great

推荐答案

要遵循 webpack 背后的理念,您需要处理从源到目标的资产.

To follow the idea behind webpack you need to process assets from your source to your target.

因此,将您的图像添加到源中的相对路径(您的条目所在的位置,本质上)并为图像添加一个加载器(也许还有其他东西)像这样:

Therefore, add your images to a relative path in your source (where your entry is, essentially) and add a loader for the images (and perhaps other things) as such:

{
    test: /\.(woff2?|jpe?g|png|gif|ico)$/, 
    use: 'file-loader?name=./assets/images/[name].[ext]'
}

只需更新输出到资产/图像的相对路径,它们应该能够加载.

Just update the relative path of the outputs to the assets/images and they should be able to load.

这篇关于使用 Webpack 提供静态图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆