Output 输出
约 556 字大约 2 分钟
2025-06-23
概念
output 位于对象最顶级键(key),包括了一组选项,指示 webpack 如何去输出、以及在哪里输出你的「bundle、asset 和其他你所打包或使用 webpack 载入的任何内容」。
常用参数
assetModuleFilename
此选项指定了非 JS 模块的名称。一般用于图片、字体、视频等静态资源。
module.exports = {
output: {
assetModuleFilename: "assets/[hash][ext][query]",
},
};
chunkFilename
此选项决定了非初始(non-initial)chunk 文件的名称。就是非入口模块的 chunk,一般指的动态导入的模块。
module.exports = {
output: {
chunkFilename: "[id].js",
// 或者使用函数
chunkFilename: (pathData) => {
return pathData.chunk.name === "main" ? "[name].js" : "[name]/[name].js";
},
},
};
clean
此选项用于在构建之前清理 output 目录。
module.exports = {
//...
output: {
clean: true, // 在生成文件之前清空 output 目录
clean: {
dry: true, // 打印, 保留应该移除的静态资源
},
clean: {
keep: /ignored\/dir\//, // 保留 'ignored/dir' 下的静态资源
},
clean: {
keep(asset) {
// 保留 'ignored/dir' 下的静态资源
return asset.includes("ignored/dir");
},
},
},
};
filename
此选项决定了每个输出 bundle 的名称。这些 bundle 将写入到 output.path
选项指定的目录下。
对于单个入口起点,filename 会是一个静态名称,我们可以使用一些占位符来生成动态名称。
常用的占位符号
[name]
: 入口起点的名称[id]
: chunk 的 id,递增[hash]
: 基于整个项目生产 hash,已禁用[chunkhash]
: 基于 chunk 内容的 hash[contenthash]
: 基于文件内容生成的 hash[query]
: query 参数[ext]
: 文件扩展名[hash:6]
: 取 hash 的前 6 位
例子
module.exports = {
//...
output: {
filename: "[name].bundle.js", // 使用入口起点的名称
},
};
path
构建产物的输出路径,物理输出路径。
module.exports = {
//...
output: {
path: path.resolve(__dirname, "dist"), // 构建产物的输出路径
},
};
publicPath
指定资源的 URL 路径,用于在浏览器中引用构建后的资源。偏向于内存中的路径。
例如,我在 github 有个仓库名字为 MyBlog
,github 分配给我的 git page 路径默认为 username.github.io/MyBlog
。
因为我们的构建产物在 username.github.io/MyBlog
下。不添加前缀 /MyBlog/
的话,会导致资源请求到 username.github.io/
,导致无法加载而报错。
module.exports = {
//...
output: {
publicPath: "/Myblog/", // 资源的 URL 路径前缀
},
};
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于