从 NUXT 布局中的“assets"目录加载 css 文件 [英] loading a css file from 'assets' directory in a NUXT layout

查看:61
本文介绍了从 NUXT 布局中的“assets"目录加载 css 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 nuxt 布局(default.vue)中,我想从资产文件夹加载图像和 css 文件图片加载成功,css文件加载不出来,为什么?

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

/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>

当我查看源代码时:

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

加载失败

还导航到 http://localhost:3000/_nuxt/assets/style.css 失败,但是 http://localhost:3000/_nuxt/assets/photo.jpg 成功

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

注意:

我不想将 style.css 放在 'static' 文件夹中,因为我想通过 webpack css-loader 加载它以添加缓存哈希

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

推荐答案

图片 src 是 Vue 自动编译的,更多内容可以在 相对路径导入;来自文档:

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

所有资源 URL,例如 <img src="...">background: url(...) 和 CSS@import 被解析为模块依赖.

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') }]
  }
}

这篇关于从 NUXT 布局中的“assets"目录加载 css 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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