HorusGoul / vite-plugin-stylex

Vite Plugin for StyleX
MIT License
110 stars 11 forks source link

vite config base with http url and vite build cause wrong stylesheet href #73

Open abrcdf1023 opened 2 months ago

abrcdf1023 commented 2 months ago

How to

  1. vite.config

    {
    base:  'https://cdn-v2.mycdn.com/dev'
    }
  2. vite build

  3. vite build with wrong href index.html

    <link rel="stylesheet" href="https:/cdn-v2.mycdn.com/dev/stylex.8751980c.css">
  4. Should be index.html

    <link rel="stylesheet" href="https://cdn-v2.mycdn.com/dev/stylex.8751980c.css">

Root Cause

publicPath = path.posix.join(
  publicBasePath,
  fileName.replace(/\\/g, "/")
);

Solution

let publicPath = ""
if (publicBasePath.startsWith("http")) {
  publicPath = new URL(fileName, publicBasePath.replace(/\/?$/, '/')).toString();
} else {
  // In Windows, we need to ensure we use posix paths to generate the correct URL for the <link> tag.
  publicPath = path.posix.join(
    publicBasePath,
    fileName.replace(/\\/g, "/")
  );
}
dan-betmate commented 1 month ago

@abrcdf1023 I've just ran into this problem, did you find a way to solve this issue? Or could you expand on your solution more? Could I use patch package?

dan-betmate commented 1 month ago

I wrote a local script to fix this, just in case anyone wants it I made a file in the root folder called fix-urls.js ` import { readFile, writeFile } from "fs/promises" import { resolve } from "path"

const fixUrls = async (filePath) => { try { const data = await readFile(filePath, "utf8") const result = data.replace(/https:\/([^/])/g, "https://$1") await writeFile(filePath, result, "utf8") console.log("URLs fixed successfully!") } catch (err) { console.error("Error processing file:", err) } }

// Adjust the path as necessary to point to your index.html or other affected files const indexPath = resolve("./dist/index.html") fixUrls(indexPath) `

And then changed my build script in package.json to this

"build": "tsc && vite build && node fix-urls.js",