devServer里 contentBase和publicPath

3,256 阅读3分钟

我的理解

  • contentBase是静态资源所在的路径,比如我们的模板index.html所在的路径,默认为项目根目录。
  • publicPath,webpack的打包输出目录,打包结果会在资源路径添加这个前缀,默认为/

例子

注意以下例子都没有借助webpack-html-plugin,而是手动添加资源的

我们举个例子,现在我们的静态文件放在了项目根目录的public文件夹下面,如图所示:

项目目录

配置1

  1. 配置 contentBasepublicPath都不配置,即使用默认值
 devServer: {},
  1. 运行

image.png

  1. 访问 http://localhost:8080/

image.png

继续访问http://localhost:8080/public

image.png

查看index.htmlmain.js的路径:

image.png

使用的是相对路径,发现它请求http://localhost:8080/public/main.js,于是我们猜想资源如果使用相对路径是相对contentBase(注意这只是一个猜想)。根据开头的理解,publicPath的默认值为/,所以我们在资源的前面添加这个前缀,修改index.html里的main.js的路径如下:

image.png

能正常访问了。

配置2

  1. 配置 配置contentBase为静态文件的路径
devServer: {
    contentBase: './public'
}
  1. 运行

image.png

  1. 访问http://localhost:8080/
  • main.js的绝对路径 资源路径添加publicPath前缀

  • main.js的相对路径

资源路径不添加publicPath前缀

惊了,发现不添加publicPath前缀都能正常访问,相当于访问http://localhost:8080/main.js,说明我们前面的猜想“资源如果使用相对路径是相对contentBase”是错误的,修正为“资源如果使用相对路径是相对浏览器URL”, 在这个例子里浏览器URL是http://localhost:8080/, 因为publicPath不配置默认为/, 所以main.js文件的位置在http://localhost:8080/main.js, 所以上面使用相对路径main.js能访问成功。于是在配置1中如果使用相对路径访问main.js文件就应该是../mian.js(因为访问路径为http://localhost:8080/public/),修改配置为配置1,重新测试如下:

image.png

果然测试成功。

配置3

  1. 配置 同时配置contentBasepublicPath
devServer: {
        contentBase: './public', // 表示静态资源的目录,比如模板index.html
        publicPath: '/dist' // 表示开发环境打包输出目录,虚拟目录,资源路径的前面会添加这个路径
    },
  1. 运行

image.png

  1. 访问http://localhost:8080/ 以下分别使用相对路径和绝对路径引入资源(下同)

image.png

image.png 解释同配置2。

当然你也可以这么配置,万变不离其宗嘛,

devServer: {
        contentBase: './public', // 表示静态资源的目录,比如模板index.html
        publicPath: '/aaa/bbb/ccc' // 表示开发环境打包输出目录,虚拟目录,资源路径的前面会添加这个路径
    },

那么资源的访问路径就是/aaa/bbb/ccc/mian.js 或者aaa/bbb/ccc/main.js

image.png

image.png

配置4

  1. 配置
devServer: {
        publicPath: '/dist' // 表示开发环境打包输出目录,虚拟目录,资源路径的前面会添加这个路径
    },
  1. 运行

image.png

  1. 访问 按照我们前面的知识,我们要访问成功肯定是访问http://localhost:8080/public/,那么我们的资源路径怎么写?2种方式:
  2. 绝对路径:老老实实地/${publicPath}/资源路径
  3. 相对路径:则我们前面猜想相对与浏览器URL, 那么这个例子中就应该是'../dist/main.js'

image.png

image.png

测试成功!

总结

  1. 使用绝对路径时,publicPath是资源的前缀
  2. 使用相对路径,是相对浏览器URL
  3. 使用绝对路径,资源里的根路径表示http://xxxx:xxxx/

以上是我自己的实践,有不对的地方还请多多指教。