如何使用网络包提供图像?



我已经读过很多关于这个的东西,但我似乎仍然无法按照我想要的方式提供我的文件。

我的文件结构:

root/
/dist/            <=  here is where webpack is putting bundles
/public/          <=  here are where all my images are stored
/src/             <=  here are my source files
template.html  <= some files under src
index.js
webpack.config.js   <=  files under root
index.html          <=  html now at root by webpack

我的 webpack.config 有这样配置的 htmlWebpackPlugin

new HtmlWebpackPlugin({
"template": "./src/template.html",
"filename": "../index.html",        <=  moved up to root?
"hash": false,
"inject": true,
"compile": true,
"favicon": false,
"minify": false,
"cache": true,
"showErrors": true,
"chunks": "all",
"excludeChunks": [],
"title": "Webpack App",
"xhtml": true,
"chunksSortMode": 'none' //fixes bug
}),

我的输出配置如下:

output: {
filename: '[name].[chunkhash:4].js',
chunkFilename: '[name].[chunkhash:4].js', //name of non-entry chunk files
path: path.resolve(__dirname, 'dist'),
publicPath: "/public"          <=  not really sure about this
},

因此,据我了解,publicPath 是图像元素上的"src"属性将在整个代码中提供的位置,对吗? 所以,在我的代码中,我可以把src='/images...'。因为"/public"将被预置。右?

另外,我读到了一些关于"webpack-dev-server"的内容,也将提供该文件夹(公共(中的文件。 开发服务器是否曾经在 webpack 创建的 dist 指令中查看过?还是完全分开的?

所以,正如你所看到的,我把索引.html移到了根目录。 不确定我是否需要这样做,但我正在尝试弄清楚如何提供我从 html 本身中调用的图像。

如何从代码"/images/..."中轻松提供我的文件。并且还直接从 HTML 中提供它们? 我应该从"公共"文件夹中提供 html 还是会影响 dist 捆绑包的服务?

使用devServer,最简单的方法是挂载你的资产目录,webpack-dev-server在幕后使用express,因此:

const express = require('express');
module.exports = {
...
devServer:{
host: '0.0.0.0',
port: 8080,
before(app) {
app.use('/assets/uploads', express.static(path.resolve('C:\temp')));
}
}
}

我的意思是,无论如何,您都可能会在生产服务器上执行类似操作。

即。location /assets/uploads { root /var/www/project; };在nginx或其他什么地方。


另一种方法是使用CopyWebPackPlugin:

new CopyWebpackPlugin(
[
{
from: path.resolve(__dirname, 'public'), 
to: path.resolve(__dirname, 'dist'),
ignore: [ 'index.html', ... ]
}
]
),

另一种方法是将图像添加到条目中某处的代码require('image1.jpg');中,并添加一个文件加载器,让 webpack 处理其余部分。 Webpack 非常灵活。如果您想知道文件夹结构,请暂时禁用 webpack-dev-server,以便您可以看到实际输出。

抱歉,我刚刚意识到我回答了您的标题问题并忽略了其他所有内容。

因此,据我了解,publicPath 是"src"属性所在的位置 图像元素将在整个代码中提供,对吗?所以 在我的代码中,我可以把src='/images...."因为"/公共"将是 预置。右?

不,publicPath 是服务器上的静态文件(生产版本(的提供位置,webpack 将需要使用该前缀的所有其他块。

另外,我读到了一些关于"webpack-dev-server"将提供文件的信息 也从该文件夹(公共(中。开发服务器是否曾经在 webpack-create dist directiory?还是完全分开的?

webpack-dev-server 服务器从内存中获取文件,所有文件都已编译。

所以,正如你所看到的,我把索引.html移到了根目录。不确定是否 我需要这样做,但我正试图弄清楚如何为我的 我从 html 本身中调用的图像。

不需要。

如何从代码"/images/..."中轻松提供我的文件。 并且还直接从 HTML 中提供它们?我应该提供 html 吗 从"公共"文件夹或影响 dist 服务的意志 束?

您可以导入图像,例如:import MyImage from './cat-image.png.

并在 img 标签中穿上 src 属性。<img src={MyImage} />

Webpack 将看到导入(您必须在 webpack 配置文件上安装和配置文件加载器(并对其进行解析。所有这些解析的图像都将输出到目标文件夹(dist 或您在输出中配置的任何内容(。

最新更新