webpack中output.publicPath是不是鸡肋?
看了官方的文档,也百度谷歌了好多文章,关于这个属性解释的不是很清楚,官方文档描述如下:
The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed <script> or <link> tags or reference assets like images, publicPath is used as the href or url() to the file when it’s different then their location on disk (as specified by path). This can be helpful when you want to host some or all output files on a different domain or on a CDN. The Webpack Dev Server also takes a hint from publicPath using it to determine where to serve the output files from. As with path you can use the [hash] substitution for a better caching profile.
在stackoverflow上也查到1个这个问题,最终结论如下:
When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.
No, this option is useful in the dev server, but its intention is for asynchronously loading script bundles in production. Say you have a very large single page application (for example Facebook). Facebook wouldn't want to serve all of its javascript every time you load the homepage, so it serves only whats needed on the homepage. Then, when you go to your profile, it loads some more javascript for that page with ajax. This option tells it where on your server to load that bundle from
亲自试验了一把,使用webpac-dev-server的时候,把a.js编译到当前目录下的bundle.js,配置中设置output.publicPath = '/assets/'; 在html文件中引用方式为<script src="/assets/mybundle.js"></script>
,浏览器访问localhost:8080可以正常访问,但是换另外1个http server就不行了,这说明webpack-dev-server会根据你请求的url路径从内存中根据这个publicPath来匹配,匹配到就找这个配置下的硬盘上的文件,实际生产环境中最多就是搞个静态资源服务器,资源都从哪里引用,或者使用CDN,如果你使用人家的CDN服务,文件也不需要你自己修改发布,如果是你自己弄静态资源服务器,JS和CSS之类常修改的,也不可能从静态服务器加载吧,正常情况下,我们开发环境按照目录建好文件,发布之后按照这个目录结构访问资源,何须多次一步啊,从各个方面我都觉得这个属性是个鸡肋,欢迎大神拍砖!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有require图片,字库等资源的时候, 就知道这个有用了
永远在尝试黑科技。 举个使用场景
在迁移旧 require 项目的时候,直接更改了 require.config 文件在测试的时候指向本地目录,然后愉快的使用 publicPath 了。
跑题了..
当静态资源需要使用cdn时,这个属性就管用了。