问题
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