loading a css file from 'assets' directory in a NUXT layout

大憨熊 提交于 2020-08-26 13:41:18

问题


in a nuxt layout (default.vue) I want to load an image and a css file from assets folder the image loaded successfully, but the css file not, why?

/layouts/default.vue

<template>
<img src="~assets/photo.jpg" />
 <!-- converted to /_nuxt/assets/photo.jpg and loaded successfully -->
</template>

<script>
export default{
 head:{
  link: [  { rel: 'stylesheet', href: '~assets/style.css' }]
}
}
</sript>

when I view the source code:

<link href="~assets/style.css" />

and it fails to be loaded

also navigating to http://localhost:3000/_nuxt/assets/style.css faild, but http://localhost:3000/_nuxt/assets/photo.jpg successed

note:

I don't want to put style.css in 'static' folder as I want to load it via webpack css-loader to add caching hashes


回答1:


The image src is automatically compiled by Vue, you can see more at relative path import; From the docs:

all asset URLs such as <img src="...">, background: url(...) and CSS @import are resolved as module dependencies.

For a custom path besides cases listed above, you need to explicitly require the path for it to be compiled as a path to static assets:

export default{
  head:{
    link: [{ rel: 'stylesheet', href: require('~assets/style.css') }]
  }
}


来源:https://stackoverflow.com/questions/53731032/loading-a-css-file-from-assets-directory-in-a-nuxt-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!