Tailwind 和 Vite 警告:“在构建时未解析,它将保持不变以在运行时解析”

Jer*_*oen 9 svelte tailwind-css vite sveltekit

我正在使用以下技术组合:

  • SvelteKit(1.5.0,使用TypeScript),以Vite(4.0.0)作为SvelteKit自带的构建工具)
  • Svelte adapter-static(2.0.1) 用于发布到 GitHub Pages
  • TailwindCSS与 Typography 插件
  • Inter字体系列来自import '../inter.css';in+layout.svelte

运行时npm run build我收到一堆警告(为了可读性换行:

/img/logo.png referenced in D:/git/my-org/my-repo/src/app.css
  didn't resolve at build time, it will remain unchanged to be resolved at runtime
Run Code Online (Sandbox Code Playgroud)
/fonts/Inter-Thin.woff2?v=3.19 referenced in D:/git/my-org/my-repo/src/inter.css
  didn't resolve at build time, it will remain unchanged to be resolved at runtime
Run Code Online (Sandbox Code Playgroud)

对我个人而言,构建输出实际上有效,并且包含所有所述资源。另外,如果我删除输出文件夹并生成一个全新的构建。我没有遇到任何问题或错误。但输出对我来说就像是警告,并且“警告是来自未来的错误”!

所以,我的问题是:上面的这条消息是什么意思,我应该将其视为警告并进行更改吗?

如何重现(使用Svelte)

这是重现上述警告的一种方法:

  1. npm create svelte@latest my-app,参见https://kit.svelte.dev/docs/creating-a-project,我选择了带有 TypeScript 和 Prettier 的“Skeleton Project”
  2. 简而言之, 请遵循https://tailwindcss.com/docs/guides/sveltekit :
    • npm install -D tailwindcss postcss autoprefixer
    • npx tailwindcss init tailwind.config.cjs -p
    • 已经vitePreprocess在我的svelte.config.ts
    • content: ['./src/**/*.{html,js,svelte,ts}']tailwind.config.js
    • @tailwind指令添加到新app.css文件并将import其添加到新+layout.svelte文件中
  3. 添加<div class="bg-[url('/favicon.png')]">Repro.</div>+page.svelte
  4. 跑步npm run build

简而言之,它似乎是由引用其他文件的任意值触发的?(此时我不确定是否严格需要 Svelte 来重现该问题,也许只需 Tailwind+Vite 就足够了?)

如何重现(不使用Svelte)

也可以不使用 Svelte,只使用 Vite 项目中的 Tailwind 来完成:

  1. 关注https://vitejs.dev/guide/ ( npm create vite@latest),选择“Vanilla”
  2. 遵循https://tailwindcss.com/docs/guides/vite但跳过 Vite 创建步骤(已完成)并从模板添加@tailwind指令style.css
  3. 添加class="bg-[url('vite.svg')]"<body>标签

同样的警告也发生在这里。


脚注:我已将我的重现添加为 Vite GitHub 问题的评论,此后该问题已被标记为已通过 PR 解决

car*_*sV2 11

似乎潜在的解决方案是在vite.config.ts文件中声明静态路径。例如:

import { resolve } from 'path';

const config: UserConfig = {
  resolve: {
    alias: {
      $fonts: resolve('./static/fonts')
    }
  }
};

export default config;
Run Code Online (Sandbox Code Playgroud)

当然,这仍然适用于其他Vite 配置(例如 javascript)。

设置此别名后,您可以在您的app.css

import { resolve } from 'path';

const config: UserConfig = {
  resolve: {
    alias: {
      $fonts: resolve('./static/fonts')
    }
  }
};

export default config;
Run Code Online (Sandbox Code Playgroud)

请注意,我提供这个答案只是为了尝试帮助任何人。然而,在另一个Stackoverflow 问题中应该归功于@HB 。