Skip to content

Commit

Permalink
Change image copying method for build process (spyder-ide#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
conradolandia authored Feb 17, 2025
1 parent 217cb11 commit 86b7daa
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 34 deletions.
72 changes: 49 additions & 23 deletions scripts/vite-plugin-copy-images.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,59 @@ import path from "path";
export default function copyImages() {
return {
name: "copy-images",
writeBundle(object, bundle) {
enforce: 'post',
apply: 'build',

configResolved(config) {
console.log('🖼️ Copy Images plugin initialized');
},

generateBundle() {
console.log('🔍 Scanning for blog posts...');
const blogDir = path.join(process.cwd(), "src", "routes", "blog");

for (const file of Object.values(bundle)) {
if (
file.fileName.endsWith(".html") &&
file.fileName.startsWith("blog/")
) {
const dirName = path.dirname(file.fileName);
const fullDirPath = path.join(blogDir, dirName.split("blog/")[1]);

const media = fs
.readdirSync(fullDirPath)
.filter((file) =>
/\.(png|jpe?g|gif|svg|webp|webm|mp4|ogv|mp3|ogg)$/i.test(file),
);

for (const medium of media) {
const content = fs.readFileSync(path.join(fullDirPath, medium));
this.emitFile({
type: "asset",
fileName: path.join(dirName, medium),
source: content,
});
try {
const blogPosts = fs.readdirSync(blogDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);

console.log('📚 Blog posts found:', blogPosts);

for (const blogPost of blogPosts) {
if (blogPost === '[page]' || blogPost === 'feed.xml') continue;

const fullDirPath = path.join(blogDir, blogPost);
console.log(`📂 Processing: ${blogPost}`);

try {
const media = fs
.readdirSync(fullDirPath)
.filter((file) =>
/\.(png|jpe?g|gif|svg|webp|webm|mp4|ogv|mp3|ogg)$/i.test(file)
);

console.log(`📸 Found ${media.length} media files in ${blogPost}`);

for (const medium of media) {
const content = fs.readFileSync(path.join(fullDirPath, medium));
const outputPath = path.join('blog', blogPost, medium);

console.log(`📦 Emitting: ${outputPath}`);
this.emitFile({
type: 'asset',
fileName: outputPath,
source: content
});
}
} catch (error) {
console.error(`❌ Error processing ${fullDirPath}:`, error);
}
}
} catch (error) {
console.error('❌ Error reading blog directory:', error);
}
},

console.log('✅ Copy Images plugin finished');
}
};
}
17 changes: 12 additions & 5 deletions src/hooks.server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { existsSync, createReadStream } from "fs";
import { join } from "path";
import { locale } from 'svelte-i18n';

export default join;
import { building } from '$app/environment';

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
Expand All @@ -11,11 +10,11 @@ export async function handle({ event, resolve }) {
locale.set(lang);
}

// Only handle image requests in development mode
if (
!building &&
event.url.pathname.startsWith("/blog/") &&
event.url.pathname.match(
/\.(png|jpe?g|gif|svg|webp|webm|mp4|ogv|mp3|ogg)$/i
)
event.url.pathname.match(/\.(png|jpe?g|gif|svg|webp|webm|mp4|ogv|mp3|ogg)$/i)
) {
const imagePath = join(process.cwd(), "src", "routes", event.url.pathname);
if (existsSync(imagePath)) {
Expand All @@ -26,3 +25,11 @@ export async function handle({ event, resolve }) {

return resolve(event);
}

/** @type {import('@sveltejs/kit').HandleServerError} */
export function handleError({ error }) {
return {
message: 'Internal Error',
code: error?.code ?? 'UNKNOWN'
};
}
14 changes: 12 additions & 2 deletions svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,30 @@ const mdsvexOptions = {
},
};

/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter(),
prerender: {
handleHttpError: "warn",
handleMissingId: "warn",
handleMissingId: "ignore",
entries: ["*"],
},
paths: {
base: process.env.NODE_ENV === "production" ? "" : "",
},
alias: {
$static: 'static'
}
},
extensions: [".svelte", ".md"],
preprocess: [mdsvex(mdsvexOptions), vitePreprocess()],
preprocess: [
vitePreprocess(),
mdsvex(mdsvexOptions)
],
vitePlugin: {
inspector: true
},
// Omit warning about screenreaders announcing <img> elements as an image
onwarn: (warning, handler) => {
// Fail the build on production if we have redundant words in the alt text
Expand Down
7 changes: 3 additions & 4 deletions vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ export default defineConfig({
plugins: [sveltekit(), copyImages()],
server: {
fs: {
allow: ['static']
allow: ['static', 'src']
}
},
build: {
target: 'esnext',
sourcemap: false,
},
chunkSizeWarningLimit: 1500,
}
});

0 comments on commit 86b7daa

Please sign in to comment.