Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

css url alias not resolved #2043

Closed
3 tasks done
mrsvt opened this issue Feb 16, 2021 · 0 comments
Closed
3 tasks done

css url alias not resolved #2043

mrsvt opened this issue Feb 16, 2021 · 0 comments

Comments

@mrsvt
Copy link

mrsvt commented Feb 16, 2021

⚠️ IMPORTANT ⚠️ Please check the following list before proceeding. If you ignore this issue template, your issue will be directly closed.

  • Read the docs.
  • Use Vite >=2.0. (1.x is no longer supported)
  • If the issue is related to 1.x -> 2.0 upgrade, read the Migration Guide first.

Describe the bug

<style>
.img {
  width: 200px;
  height: 200px;
  background: url("@/assets/logo.png") center / contain no-repeat;
}
</style>

The alias (@) is not resolved to its correct path defined in vite.config.js:

import path from "path";
import vue from "@vitejs/plugin-vue";

/**
 * @type {import('vite').UserConfig}
 */
export default {
  resolve: {
    alias: {
      "@": path.join(__dirname, "src"),
    },
  },
  plugins: [vue()],
};

I tried to fix it in assets.ts with the following:

-  const file = url.startsWith('/')
-    ? path.join(config.root, url)
-    : path.join(path.dirname(importer), url)
+  let file
+  if (url.startsWith('/')) {
+    file = path.join(config.root, url)
+  } else {
+    const resolved = (await pluginContext.resolve(url, importer))?.id
+    file = resolved || path.join(path.dirname(importer), url)
+  }

and in css.ts with the following:

-    ? (url, importer) => {
+    ? async (url, importer) => {
        if (url.startsWith('/')) {
          return config.base + url.slice(1)
        } else {
-          const filePath = normalizePath(
-            path.resolve(path.dirname(importer || id), url)
-          )
+          const resolved = (await this.resolve(url, importer || id))?.id
+          const filePath =
+            resolved ||
+            normalizePath(path.resolve(path.dirname(importer || id), url))
          return fileToDevUrl(filePath, config)
        }
      }

Reproduction

https://github.com/sayuti-daniel/vite-css-url-alias

System Info

  • vite version: 2.0.0-beta.70
  • Operating System: MacOS Catalina (10.15.7)
  • Node version: v14.15.0
  • Package manager (npm/yarn/pnpm) and version: npm 6.14.8

Logs (Optional if provided reproduction)

  1. Run vite or vite build with the --debug flag.
  2. Provide the error log here.
@github-actions github-actions bot locked and limited conversation to collaborators Jul 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant