gpt4 book ai didi

html - 如何使用 webpack 服务图像?

转载 作者:行者123 更新时间:2023-12-04 13:21:52 25 4
gpt4 key购买 nike

我已经阅读了很多这方面的资料,但我似乎仍然无法按照我想要的方式提供我的文件。

我的文件结构:

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”的内容也将提供该文件夹(公共(public))中的文件。开发服务器是否查看过 webpack 创建的 dist 目录?还是完全分开?

因此,如您所见,我将 index.html 移到了根目录。不确定我是否需要这样做,但我正在尝试弄清楚如何提供我从 html 本身调用的图像。

如何从代码“/images/....”中轻松提供我的文件,并直接从 html 提供它们?我应该从“公共(public)”文件夹提供 html 还是会影响 dist 包的服务?

最佳答案

使用 devServer 可能最简单的方法就是挂载你的 assets-directory。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 以便您可以看到实际输出。

抱歉,我刚刚意识到我回答了你的标题问题而忽略了其他一切。

关于html - 如何使用 webpack 服务图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51013035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com