问题描述:
在使用webpack5+three.js写vue3插件时候,在加载hdr环境贴图使用的绝对路径无法正确加载
main.js?be46:51335 THREE.RGBELoader Bad File Format: bad initial token // 加载hdr图片失败
main.js?be46:65347 SyntaxError: Unexpected token < in JSON at position 0 // 加载模型失败
at JSON.parse (<anonymous>)
at GLTFLoader.parse (main.js?be46:65347)
at Object.eval [as onLoad] (main.js?be46:65347)
at XMLHttpRequest.eval (main.js?be46:38063)
_onError @ main.js?be46:65347
原因分析:
我这里是把插件放入vue中public中没有发布,在public中相当于二个环境静态资源
在外面使用静态资源时我们默认在vue中获取的是 http://localhost:8080/vill/static.xxx来获取插件静态资源
// webpack简单配置处理hdr
{
test: /\.hdr$/,
type: "asset/resource",
generator: {
filename: "hdr/[name].hdr"
},
},
// 页面调用出现
import hdr from "../../static/environment/equirectangular/venice_sunset_1k.hdr";
console.log(hdr); // hdr/venice_sunset_1k.hdr
// 如果是hdr/venice_sunset_1k.hdr路径在vue中使用就会报错
// 因为在vue的静态路径是vue中
http://localhost:8080/vill.hdr/venice_sunset_1k.hdr
// 实际路径
http://localhost:8080/hdr/venice_sunset_1k.hdr
二者对比缺少外围路径
解决方案:
在webpack官网发现
output.publicPath
这个属性,简单点说就是修改根目录(最外层路径)
官方解释
output.publicPath
Type:
function
string
targets 设置为 web 与 web-worker 时 output.publicPath 默认为 'auto',查看该指南获取其用例
对于按需加载(on-demand-load)或加载外部资源(external resources)(如图片、文件等)来说,output.publicPath 是很重要的选项。如果指定了一个错误的值,则在加载这些资源时会收到 404 错误。
此选项指定在浏览器中所引用的「此输出目录对应的公开 URL」。相对 URL(relative URL) 会被相对于 HTML 页面(或 <base> 标签)解析。相对于服务的 URL(Server-relative URL),相对于协议的 URL(protocol-relative URL) 或绝对 URL(absolute URL) 也可是可能用到的,或者有时必须用到,例如:当将资源托管到 CDN 时。
该选项的值是以 runtime(运行时) 或 loader(载入时) 所创建的每个 URL 为前缀。因此,在多数情况下,此选项的值都会以 / 结束。
规则如下:output.path 中的 URL 以 HTML 页面为基准。
我们设置publicPath来指定最外层
output: {
publicPath: process.env.NODE_ENV === "development" ? "vill" : "", // 使用这一行来设置
},
以上就是自己的一点点见解,如有错误,麻烦大佬指出