vue.js应用程序中静态资产的路径 [英] Path to static assets in vue.js application

查看:137
本文介绍了vue.js应用程序中静态资产的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于vue-cli Webpack模板开发单页应用程序.由于我们还必须使用静态资产,因此我们需要在样式表中引用它们.

I am developing a single page application based on the vue-cli webpack template. Since we have to use static assets as well, we need to reference them in our stylesheet.

官方文档建议使用如下绝对路径:

The official documentation recommends to use an absolute path like the following one:

background-image: url('/assets/images/lo/example2.svg');

问题在于,静态资产不会由vue-loader和Webpack本身处理,因此在最终输出样式表中无法正确设置网址.根据您的publicPath配置,将由webpack网址加载程序处理的所有资产都将获得正确的相对网址.静态资产也需要同样的效果.

The problem is, that static assets won't be processed by the vue-loader and webpack itself, so the urls won't be set correctly in the final output stylesheet. All assets that will be processed by the webpack url-loader will get the correct relative url depending on your publicPath configuration. The same effect is desired for static assets.

您是否知道如何将静态资产与基于vue.js的应用程序结合使用?

Do you have any idea how to use static assets in combination with a vue.js-based application?

更新

经过研究和反复试验,我决定将最终的样式表和脚本包放在index.html旁边的根文件夹中.生成的路径将正常工作.这不是最佳的解决方案,因为我更喜欢脚本和样式表的子文件夹(尽管它们只包含一个文件).但是,尽管如此,我仍然拥有一个生成一致且有效的工件的构建过程.

After researching and a lot of trial and error I've decided to place the final stylesheet and the script bundle inside the root folder next to the index.html. The generated paths will work properly. Not the most optimal solution, since I prefer subfolders for scripts and stylesheet (despite they contain only one file). But nevertheless I have a build process that generates consistent and valid artifacts.

推荐答案

对于真实"静态资产,请使用静态目录.

For "real" static assets, use the static directory.

相比之下,Webpack根本不处理static/中的文件:它们使用相同的文件名直接复制到最终目的地.您必须使用绝对路径引用这些文件,该绝对路径是通过在config.js中加入build.assetsPublicPath和build.assetsSubDirectory来确定的.

In comparison, files in static/ are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename. You must reference these files using absolute paths, which is determined by joining build.assetsPublicPath and build.assetsSubDirectory in config.js.

您还可以在config/index.js中覆盖此默认路径

You can also overwrite this default path in config/index.js

module.exports = {
  // ...
  build: {
    assetsPublicPath: '/',
    assetsSubDirectory: 'static'
  }
}

放置在static/中的任何文件都应使用绝对URL/static/[文件名]进行引用.如果将assetSubDirectory更改为资产,则这些URL将需要更改为/assets/[文件名].

Any file placed in static/ should be referenced using the absolute URL /static/[filename]. If you change assetSubDirectory to assets, then these URLs will need to be changed to /assets/[filename].

这篇关于vue.js应用程序中静态资产的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆