是否有一种方法可以提示webpack相对于根据需要生成文件的文件来生成输出文件?假设我有以下配置:
let indexHTML = new HtmlWebpackPlugin({
template: "./src/pug/index.pug",
filename: 'index.html',
})
let iframeExample = new HtmlWebpackPlugin({
template: "./src/pug/iframe-example.pug",
filename: 'examples/index.html',
})
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.join(__dirname, "/dist"),
},
entry: {
index: "./src/js/index.js",
},
plugins: [
new CleanWebpackPlugin(),
indexHTML,
iframeExample
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'file-loader',
options: {
name: "[name].[ext]",
outputPath: "css",
esModule: false,
}
}
]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "imgs",
esModule: false,
}
}
},
{
test: /\.(aac|mp3)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "audio",
esModule: false
}
}
},
{
test: /\.(webm|mp4)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "video",
esModule: false
}
}
},
]
},
});
在此配置中,HtmlWebpackPlugin生成两个html页面:一个是'dist / index.html'('dist /'是我的输出文件夹),另一个是'dist / examples / index.html'(即' HtmlWebpackPlugin将为我创建的“ examples /”文件夹中的index.html”)。
[当文件加载器在我生成的html文件中遇到require / import语句时,它将尝试将其解析为url,并将该文件从我的工作文件夹结构复制到输出文件夹中。在文件加载器的outputPath中,我为输出内容(“ imgs”,“视频”等)指定了相对路径,该路径将作为文件加载器生成的每个URL的前缀,从而在每个对应的html中产生相对URL 。
问题是,文件夹本身将在输出文件夹中生成(在我的情况下为'dist'),而不是在输出文件夹结构中出现相应html的位置。也就是说,在'dist / examples / index.html'中引用的所有.css文件都将被放入'dist / css /'文件夹中,因此不会在'dist / examples / index.html'中看到,该文件仅包含相对路径('css /')。
要重申我的问题:如何使webpack生成相对于引用位置的输出文件?也就是说,我希望文件加载器将'dist / examples / index.html'中引用的所有.css文件输出到'/ dist / examples / css /'。
您可以从webpack的输出对象中使用publicPath,
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.join(__dirname, "/dist"),
publicPath: 'https://test.org/example/'
},
..
..
上述更改将使两个index.html文件在生产中都具有相同的相对路径。
index.html
<script type="text/javascript" src="https://test.org/example/test.js"></script>
examples / index.html
<script type="text/javascript" src="https://test.org/example/test.js"></script>
有关publicPath的更多信息,请参考答案https://stackoverflow.com/a/38748466/3679048