我看过很多关于这方面的东西,但我似乎还是不能用我想要的方式来处理我的文件。
我的文件结构:
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
我的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-开发服务器’将服务于该文件夹(公共)的文件。开发服务器有没有看过webpack创建的dist目录?还是完全分开了?
因此,正如您所看到的,我将index.html移至根目录。我不确定是否需要这样做,但我正在努力弄清楚如何在html本身中为我调用的图像服务。
如何在代码‘/映像/.’中轻松地提供文件?也直接从html中为他们服务?我应该从‘公用’文件夹提供html,还是会影响dist包的服务?
发布于 2018-06-24 18:12:02
使用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服务器,这样您就可以看到实际的输出。
抱歉,我刚意识到我回答了你的标题问题而忽略了其他的一切。
发布于 2018-06-24 17:57:34
因此,据我所知,在publicPath中,图像元素上的"src“属性将从整个代码中得到服务,对吗?所以,在我的代码中,我可以将src=‘/images.’因为'/public‘将占上风。对吗?
不,publicPath是您服务器上的静态文件(产品构建)服务的来源,webpack将使用该前缀要求所有其他块。
此外,我还读到了一些关于‘webpack-开发服务器’将服务于该文件夹(公共)的文件。开发服务器有没有看过webpack创建的dist目录?还是完全分开了?
webpack服务器服务器文件从内存中编译,全部文件编译完毕.
因此,正如您所看到的,我将index.html移至根目录。我不确定是否需要这样做,但我正在努力弄清楚如何在html本身中为我调用的图像服务。
不需要。
如何在代码‘/映像/.’中轻松地提供文件?也直接从html中为他们服务?我应该从‘公用’文件夹提供html,还是会影响dist包的服务?
您可以导入您的图像,如:import MyImage from './cat-image.png
。
并在img标记中插入src攻击。<img src={MyImage} />
Webpack将看到导入(您必须安装文件加载程序并配置在webpack配置文件上),并对其进行解析。所有被解析的图像都将输出到目标文件夹(dist或您在输出中配置的任何内容)。
https://stackoverflow.com/questions/51013035
复制相似问题