如何从nuxt.js中的assets文件夹导入css文件

obl*_*lla 5 css vue.js nuxt.js

<template>
  <div class="container">
    <head>
      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />
    </head>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

像上面那样导入 css 会导致此错误

vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)

除了将整个 css 放在模板中之外,真的没有其他方法加载 css 吗?

Hen*_*ren 14

你需要知道的第一件事是,你不能在任何地方声明一个 html 头,既不能在你的模板中,也不能在你的组件中,也不能在你的页面中,也不能在任何地方。

请记住,您不能为此使用 html 标签,您将使用 json 模式。

查看https://nuxtjs.org/guide/configuration以获得更详细的解释。

现在你怀疑是否要全局导入 CSS,正确的位置是在你的 nuxt.config.js 中,在这个文件中,你有一个名为 head 的属性,在 head 中我们将配置所有导入。

因此,在 nuxt.config.js 中找到您的头部会话,然后创建名为 css 的新属性,如下所示:

   head: {
     css: [
       '~/assets/style/app.styl',
       '~/assets/style/main.css'
     ],
   }
   ...
Run Code Online (Sandbox Code Playgroud)

另一种方法是直接在组件中导入 css,为此您可以执行以下操作:

        <style scoped>
        @import '~/assets/style/main.css';
        </style>
    OR
        <style scoped src="@/assets/styles/mystyles.css">
        </style>
Run Code Online (Sandbox Code Playgroud)

在 Nuxt 中,您还需要在应用程序中安装 CSS 加载器,因此请确保在应用程序中安装了“stylus”和“stylus-loader”。