网络编程
位置:首页>> 网络编程>> JavaScript>> Webpack path与publicPath的区别详解

Webpack path与publicPath的区别详解

作者:HeliumLau  发布时间:2024-04-29 13:37:49 

标签:Webpack,path,publicPath

前言

在webpack模块化开发的过程中,发现webpack.config.js配置文件的输出路径总有一个path与publicPath,不解其意。


module.exports = {
output: {
path: path.resolve("./examples/dist"),
filename: "app.js",
publicPath: "What should I put here?"
}
}

正文

官方解释

publicPath: The output.path from the view of the Javascript / HTML page.

从JS/HTML页面来看的输出路径

我的理解

output.path 储存你所有输出文件的本地文件目录。(绝对路径)

举个例子:


path.join(__dirname, “build/”)

webpack将会把所有的文件输出到localdisk/path-to-your-project/build/

output.publicPath

你上传所有打包文件的位置(相对于服务器根目录)

path:用来存放打包后文件的输出目录

publicPath:指定资源文件引用的目录

用处:例如在express中,指定了public/dist是网站的根目录,网站的源文件存放在public中,那么就需要设置path:”./dist”指定打包输出到该目录,而publicPath就需要设置为”/”,表示当前路径。

publicPath取决于你的网站根目录的位置,因为打包的文件都在网站根目录了,这些文件的引用都是基于该目录的。假设网站根目录为public,引用的图片路径是'./img.png',如果publicPath为'/',图片显示不了,因为图片都打包放在了dist中,那么你就要把publicPath设置为”/dist”。

举个例子:

/assets/

假设你将这个工程部署在服务器 http://server/

通过将output.publicPath设置为/assets/,这个工程将会在http://server/assets/找到webpack资源。

在这种前提下,所有与webpack相关的路径都会被重写成以/assets/开头。


src="picture.jpg" Re-writes ➡ src="/assets/picture.jpg"

Accessed by: (http://server/assets/picture.jpg)

src="/img/picture.jpg" Re-writes ➡ src="/assets/img/picture.jpg"

Accessed by: (http://server/assets/img/picture.jpg)

重要

如果你在用style-loader或者css sourceMap,你就需要设置publicPath。把它设置成服务器地址的绝对路径,比如http://server/assets/,这样资源可以被正确加载。

来源:https://blog.csdn.net/HeliumLau/article/details/70666433

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com