output

publicPath

  1. 静态资源最终访问路径 = output.publicPath + 资源loader或插件等配置路径
output.publicPath = '/dist/'

// image
options: {
     name: 'img/[name].[ext]?[hash]'
}

// 最终图片的访问路径为
output.publicPath + 'img/[name].[ext]?[hash]' = '/dist/img/[name].[ext]?[hash]'

// js output.filename
output: {
    filename: '[name].js'
}
// 最终js的访问路径为
output.publicPath + '[name].js' = '/dist/[name].js'

// extract-text-webpack-plugin css
new ExtractTextPlugin({
    filename: 'style.[chunkhash].css'
})
// 最终css的访问路径为
output.publicPath + 'style.[chunkhash].css' = '/dist/style.[chunkhash].css'

这个最终静态资源访问路径在使用html-webpack-plugin打包后得到的html中可以看到。所以publicPath设置成相对路径后,相对路径是相对于build之后的index.html的,例如,如果设置publicPath: './dist/',则打包后js的引用路径为./dist/main.js,但是这里有一个问题,相对路径在访问本地时可以,但是如果将静态资源托管到CDN上则访问路径显然不能使用相对路径,但是如果将publicPath设置成/,则打包后访问路径为localhost:8080/dist/main.js,本地无法访问
所以这里需要在上线时候手动更改publicPath,感觉不是很方便,但是该如何解决…

一般情况下publicPath应该以’/‘结尾,而其他loader或插件的配置不要以’/‘开头

webpack-dev-server

publicPath

在开发阶段,我们借用devServer启动一个开发服务器进行开发,这里也会配置一个publicPath,这里的publicPath路径下的打包文件可以在浏览器中访问。而静态资源仍然使用output.publicPath
webpack-dev-server打包的内容是放在内存中的,这些打包后的资源对外的的根目录就是publicPath,换句话说,这里我们设置的是打包后资源存放的位置

// 假设devServer的publicPath为
const publicPath = '/dist/'
// 则启动devServer后index.html的位置为
const htmlPath = `${pablicPath}index.html`
// 包的位置
cosnt mainJsPath = `${pablicPath}main.js`
  1. 当你不配置devServer下的publicPath时,其会默认将包打到output.publicPath的路径下。
  2. 当你配置了devServer下的publicPath时,才其会将包打开你指定的路径下。

    devServer.publicPath & devServer.contentBase

  • devServer.contentBase 告诉服务器从哪里提供内容。只有在你想要提供静态文件时才需要。
  • devServer.publicPath 将用于确定应该从哪里提供 bundle,并且此选项优先。

contextBase

代表html页面所在的相对目录,如果我们不配置项,devServer默认html所在的目录就是项目的根目录,这个时候启动服务,访问地址通常会出现下面这样的场面:
image.png

总结

  1. output的publicPath是用来给生成的静态资源路径添加前缀的;
  2. devServer中的publicPath是用来本地服务拦截带publicPath开头的请求的;
  3. contentBase是用来指定被访问html页面所在目录的;