richardtallent / vite-plugin-singlefile

Vite plugin for inlining JavaScript and CSS resources
MIT License
808 stars 53 forks source link

plugin don't respect basename from vite config #75

Closed yslpn closed 8 months ago

yslpn commented 1 year ago

My config:


import { defineConfig } from "vite";
import preact from "@preact/preset-vite";

import { viteSingleFile } from "vite-plugin-singlefile"
import { createHtmlPlugin } from "vite-plugin-html";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [preact(), createHtmlPlugin(), viteSingleFile({ removeViteModuleLoader: true })],
  base: "/shri2023-performance/",
});

My css:

.event__icon_temp {
  background-image: url(assets/icon_temperature.svg);
}

I got link like this:

background-image:url(/assets/icon_temperature-b86a9b9d.svg)

Expected result:

background-image:url(/shri2023-performance/assets/icon_temperature-b86a9b9d.svg)

waapiti commented 1 year ago

Same thing happens to me, any solution?

brunnock commented 1 year ago

Same. Although, I'm trying to set base to an empty string.

richardtallent commented 1 year ago

If you can create a repo that reproduces this issue and does not reproduce this issue when used without this plugin, I can take a look when I return after Sept. 8.

If this is something Vite/rollup are doing, I don't have answers. The intent of this plugin is to create a single file, not to rewire relative paths for links to external files.

GatienBouyer commented 1 year ago

I encountered the same issue when trying to open the index.html from my browser.

The line below is the source of the issue:

const _useRecommendedBuildConfig = (config: UserConfig) => {
    // ...
    // Subfolder bases are not supported, and shouldn't be needed because we're embedding everything.
   config.base = undefined

https://github.com/richardtallent/vite-plugin-singlefile/blob/16e7e38c2abe12828d1294fb760d511bb9e866fb/src/index.ts#L117C2

I commented that line, even if using viteSingleFile({ useRecommendedBuildConfig: false }) should be preferred. In my case, I use relative paths i.e. ./ as basename, which is indeed used in the output.

However, commenting this line didn't solve entirely my problem. I use SVG files that are referenced by: new URL("../vite.svg",import.meta.url). As the plugin inline the code, the import.meta.url no longer refers to the correct location.

My workaround: adding the code below in the replaceScript function and replacing newCode by fixedNewCode.

const fixedNewCode = `import.meta.url = import.meta.url.substring(0, import.meta.url.lastIndexOf("/")+1) + "${scriptFilename}";` + newCode;
richardtallent commented 8 months ago

This has been addressed in v1.0. However, there are a a few breaking changes in that release as well, so caveat emptor!