使用Parcel时如何为脚本src添加路径前缀
在Parcel中配置静态资源路径前缀的方法
完全可以通过package.json添加配置实现这个需求,Parcel提供了publicUrl字段来统一设置所有打包后资源的路径前缀,具体操作如下:
- 打开项目根目录的
package.json文件,在顶层JSON结构中添加publicUrl字段,值设为你需要的路径前缀/path:
{ "name": "your-project", "version": "1.0.0", "publicUrl": "/path", "scripts": { "build": "parcel build index.html" } }
- 执行生产构建命令
npm run build后,生成的index.html中,所有打包后的.js和.css资源路径都会自动带上/path前缀,比如:
<script type="module" src="/path/index.a1b2c3.js" defer></script> <link rel="stylesheet" href="/path/index.d4e5f6.css">
如果需要仅在生产环境生效该配置,也可以在build脚本中通过命令行参数指定,替代package.json中的字段:
{ "scripts": { "build": "parcel build index.html --public-url /path" } }
内容的提问来源于stack exchange,提问作者mrwuscience
相关产品推荐
相关产品推荐

