Embed Directive in TypeScript
Our first example demonstrates how to embed files and folders into a TypeScript application using a bundler like Webpack or Rollup. While TypeScript doesn’t have a direct equivalent to Go’s //go:embed directive, we can achieve similar functionality using module bundlers.
First, let’s set up our project structure:
project/
├── src/
│ ├── main.ts
│ └── folder/
│ ├── single_file.txt
│ ├── file1.hash
│ └── file2.hash
└── package.jsonNow, let’s create our main.ts file:
// Import the contents of single_file.txt as a string
import fileString from './folder/single_file.txt';
// Import the contents of single_file.txt as a Uint8Array
import fileByte from './folder/single_file.txt?raw';
// Import multiple files using a dynamic import
async function loadFiles() {
const folder = import.meta.glob('./folder/*');
console.log(fileString);
console.log(new TextDecoder().decode(fileByte));
const file1Content = await folder['./folder/file1.hash']();
console.log(file1Content.default);
const file2Content = await folder['./folder/file2.hash']();
console.log(file2Content.default);
}
loadFiles();To make this work, you’ll need to configure your bundler to handle different file types. Here’s an example configuration for Vite, a popular build tool that works well with TypeScript:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [],
assetsInclude: ['**/*.txt', '**/*.hash'],
});This configuration tells Vite to treat .txt and .hash files as assets, allowing them to be imported in our TypeScript code.
To run the example:
- Create the necessary files:
$ mkdir -p src/folder
$ echo "hello typescript" > src/folder/single_file.txt
$ echo "123" > src/folder/file1.hash
$ echo "456" > src/folder/file2.hash- Install dependencies and run the development server:
$ npm init -y
$ npm install vite typescript
$ npx viteWhen you run the application, you should see the following output:
hello typescript
hello typescript
123
456This example demonstrates how to embed file contents directly into your TypeScript application using a module bundler. While it’s not exactly the same as Go’s embed directive, it achieves similar functionality by allowing you to include file contents in your bundled application.
Comments powered by Disqus