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

fix: let vite create final paths #400

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/two-games-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vite-imagetools': patch
---

Let vite create correct paths in build result
25 changes: 15 additions & 10 deletions packages/vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function imagetools(userOptions: Partial<VitePluginOptions> = {}): Plugin

let directives = srcURL.searchParams

if(typeof pluginOptions.defaultDirectives === "function") {
if (typeof pluginOptions.defaultDirectives === 'function') {
directives = new URLSearchParams([...pluginOptions.defaultDirectives(srcURL), ...srcURL.searchParams])
} else if (pluginOptions.defaultDirectives) {
directives = new URLSearchParams([...pluginOptions.defaultDirectives, ...srcURL.searchParams])
Expand Down Expand Up @@ -83,7 +83,7 @@ export function imagetools(userOptions: Partial<VitePluginOptions> = {}): Plugin
type: 'asset'
})

metadata.src = `__VITE_IMAGE_ASSET__${fileHandle}__`
metadata.src = `__VITE_ASSET__${fileHandle}__`
} else {
metadata.src = posix.join('/@imagetools', id)
}
Expand Down Expand Up @@ -137,19 +137,24 @@ export function imagetools(userOptions: Partial<VitePluginOptions> = {}): Plugin
},

renderChunk(code) {
const assetUrlRE = /__VITE_IMAGE_ASSET__([a-z\d]{8})__(?:_(.*?)__)?/g
const assetUrlRE = /const\s+(\S+)\s*=\s*"((__VITE_ASSET__([a-z\d]{8})__ \d+w,?\s?)+)";/g
benmccann marked this conversation as resolved.
Show resolved Hide resolved

let match
let s
while ((match = assetUrlRE.exec(code))) {
s = s || (s = new MagicString(code))
const [full, hash, postfix = ''] = match

const file = this.getFileName(hash)

const outputFilepath = viteConfig.base + file + postfix

s.overwrite(match.index, match.index + full.length, outputFilepath)
const [full, name, assets] = match
const parts = assets.split(',').flatMap((s, is, as) =>
s
.trim()
.split(' ')
.map((v, i, a) => (i === a.length - 1 && is < as.length - 1 ? v + ',' : v))
)
const output = [
...parts.map((part, index) => `const ${name}__${index} = ${JSON.stringify(part)};`),
`const ${name} = [${parts.map((part, index) => `${name}__${index}`).join(', ')}].join(" ");`
].join('\n')
s.overwrite(match.index, match.index + full.length, output)
}

if (s) {
Expand Down