phillip-le / phillip-le.github.io

https://phillip-le.github.io/
1 stars 0 forks source link

How to import other file types as text in TypeScript #99

Closed phillip-le closed 3 weeks ago

phillip-le commented 1 month ago

Example is importing an XML file as a string to serve static RSS feed on GET.

TypeScript: Add a type declaration ESBuild: Use the file loader

vite:

import { readFileSync } from 'fs';

const xmlRegEx = /\.xml$/;

const xmlLoaderPlugin = {
  name: 'xml-loader',
  async transform(_ : string, id : string) {
    if (xmlRegEx.test(id)) {
      // double check if you can use the `async` version
      const xml = readFileSync(id).toString();
      return {
        code: `export default \`${xml}\``,
      };
    }
    return {};
  }
}

Inspiration: https://github.com/lorenzoc25/vite-plugin-xml-loader