motherload README

README проекта с github.com/colinhacks/motherload. Одним файлом markdown: README.md.


Motherload

Import data files into TypeScript, fully typed
by @colinhacks


stars


Motherload is a set of TypeScript loaders for data formats: import a TOML, YAML, JSONC, JSON5, CSV, TSV, Markdown, text or .env file and get a typed module.

It's powered by TypeScript's content mappers (introduced [email protected]). These are like plugins for TypeScript, and it lets Motherload provide full static types for the imported data, in a way that natively integrates with tsc.

Setup

Motherload needs:

npm install -D motherload typescript@beta

An app that runs under the preload, not as a bundle, loads its data files at run time, so it installs Motherload as a dependency: npm install motherload.

Name Motherload in tsconfig.json, with the extensions it should own, and type-check with --runExternalCode, the flag that lets tsc run content mappers:

// tsconfig.json
{
  "compilerOptions": { /* ... */ },
  "contentMappers": [
    {
      "package": "motherload",
      "extensions": [
        ".toml", ".yaml", ".yml", ".jsonc", ".json5", ".env",
        ".csv", ".tsv", ".txt", ".md"
      ]
    }
  ]
}
// package.json
{
  "scripts": {
    "typecheck": "tsc --noEmit --runExternalCode"
  }
}

Load Motherload when your code runs, so that a data-file import works at run time too. On Node:

node --import motherload/register main.ts
Runtime or bundler Setup
Bun preload = ["motherload/register"] in bunfig.toml
nub "preload": ["motherload/register"] in nub.jsonc
Vite, Vitest, Rollup, Rolldown import motherload from "motherload/vite", then motherload() in plugins
esbuild, Bun.build import motherload from "motherload/esbuild", then motherload() in plugins
webpack, Rspack use: "motherload/webpack" in a rule for the data files, in module.rules
Next.js import { withMotherload } from "motherload/next", then export default withMotherload(nextConfig): the loader for Turbopack and webpack, and the type check inside next build (setup)
Jest "motherload/jest" in transform, for the data files (setup)

Each setup has a working example project to copy: examples.

In VS Code or Cursor, install the TypeScript 7 extension (TypeScriptTeam.native-preview) and point it at your project's TypeScript, since the extension bundles TypeScript 7.0:

// .vscode/settings.json
{
  "js/ts.experimental.useTsgo": true,
  "js/ts.tsdk.path": "./node_modules/typescript"
}

Then trust the workspace, and click Allow when the extension asks to use the workspace's TypeScript. Zed takes a few more settings: see Editors.

The motherload package provides one unified content mapper for all data formats. You can also consume them à la carte.

Loaders

Each file is parsed when the module is built, so a bundle holds the data and no parser. The default export is the data, typed as as const would type it.

.toml

name = "demo"
port = 8080

[server]
host = "localhost"
import config from "./config.toml";
// config: {
//   readonly name: "demo";
//   readonly port: 8080;
//   readonly server: { readonly host: "localhost" };
// }

.yaml

Motherload reads .yaml and .yml files:

- name: Ada
  role: admin
- name: Grace
  role: member
import team from "./team.yaml";
// team: readonly [
//   { readonly name: "Ada"; readonly role: "admin" },
//   { readonly name: "Grace"; readonly role: "member" },
// ]

A file of several documents, separated by ---, is the list of them:

kind: Service
---
kind: Deployment
replicas: 2
import deploy from "./deploy.yaml";
// deploy: readonly [
//   { readonly kind: "Service" },
//   { readonly kind: "Deployment"; readonly replicas: 2 },
// ]

.jsonc

{
  // the editor's font size
  "fontSize": 14,
  "exclude": ["dist",],
}
import settings from "./settings.jsonc";
// settings: {
//   readonly fontSize: 14;
//   readonly exclude: readonly ["dist"];
// }

.json5

{
  // shown on the sign-in page
  welcome: 'Welcome back',
  retries: 3,
}
import strings from "./strings.json5";
// strings: { readonly welcome: "Welcome back"; readonly retries: 3 }

[!NOTE] To import a JSON Schema file, .schema.jsonc or .schema.json5, as its type and a validator, use dotschema.

.env

Importing a .env file sets its variables on process.env when the module runs, and types each of them as a string:

DATABASE_URL=postgres://localhost/app
PORT=3000
import "./.env";

process.env.DATABASE_URL; // string
process.env.PORT;         // string

[!NOTE] Importing a .env file suits a script you run where the file is, such as a seed or a migration on your own machine. An application is often built where the file is not, in CI or on a host, and a missing file fails the build.

A variable the environment already sets keeps its value, and a bundle holds none of the file's values.

A file whose name ends in .env, such as local.env, needs no setup. Imported first, its values win over .env's:

import "./local.env";
import "./.env";

Any other name, such as .env.local, goes in extensions in full:

{ "package": "motherload", "extensions": [".env", ".env.local" /* ... */] }

A bundle reads no .env file, since it runs wherever it is deployed. It takes its variables from the environment there, and stops at startup if one the file declares is unset, so on your own machine it runs with the file passed to Node:

node --env-file=.env dist/main.mjs

.csv

The header names the columns, and every value is a string, as written.

name,email
Ada,[email protected]
Grace,[email protected]
import users from "./users.csv";
// users: readonly {
//   readonly name: string;
//   readonly email: string;
// }[]

.tsv

The same as .csv, with a tab between fields.

player	score
Ada	42
Grace	37
import scores from "./scores.tsv";
// scores: readonly {
//   readonly player: string;
//   readonly score: string;
// }[]

.txt

Notes from the lab.
import notes from "./notes.txt";
// notes: string

.md

Importing a .md file gives its frontmatter, typed from the file, and its Markdown body:

---
title: Hello
draft: false
---
# Hello

The body of the post.
import post from "./post.md";
// post: {
//   readonly md: string;
//   readonly frontmatter: {
//     readonly title: "Hello";
//     readonly draft: false;
//   };
// }

Each part is also a named export, so a bundle that imports the frontmatter alone leaves out the body:

import { frontmatter } from "./post.md";

Errors

Invalid data in a file is a type error, at the line and column of the problem:

$ tsc --noEmit --runExternalCode
users.csv:3:1 - error motherload1: This row has 3 fields; the header has 2.

3 Grace,[email protected],extra
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

motherload (colinhacks/motherload)

Ищем в базе…

Что это такое?Motherload — это набор загрузчиков для TypeScript, которые позволяют импортировать прямо в код файлы с данными (TOML, YAML, JSON5, CSV, TSV, Markdown, обычный текст или .env) и получать полностью типизированный модуль. Работает на основе новой возможности TypeScript под названием content mappers.
Это возможность компилятора или пакет, который я устанавливаю?Это npm-пакет, который работает как плагин для tsc (content mapper), чтобы средство проверки типов TypeScript знало структуру ваших данных, а также соответствующий загрузчик времени выполнения для того сборщика или среды, которая на самом деле читает файл.
Как мне добавить это в проект?Установите его командой `npm install motherload`, затем в tsconfig.json зарегистрируйте расширения файлов, которыми он должен заниматься, с флагом `--runExternalCode`, а после этого подключите соответствующий загрузчик времени выполнения для вашего стека (предзагрузка Bun, предзагрузка nub, плагин Vite/Vitest/Rollup, плагин esbuild, правило webpack, обёртка Next.js или трансформер Jest).
Нужна ли мне особая версия TypeScript?Да: Motherload требует TypeScript 7.1 beta или новее (первый выпуск с content mappers) и Node 24+, либо Bun, либо nub.
Если настроить всё только в tsconfig, импорт будет работать во время выполнения?Нет: проверка типов и сам импорт во время выполнения настраиваются отдельно. Нужно ещё зарегистрировать загрузчик Motherload для вашей среды или сборщика, иначе файл пройдёт проверку типов, но не загрузится, когда код будет выполняться.
Какие форматы файлов может импортировать Motherload?TOML, YAML/YML, JSONC, JSON5, CSV, TSV, обычный текст, Markdown (с типизированным фронтматтером) и файлы .env.
Что будет, если в файле с данными неверное содержимое?Это появится как ошибка типа TypeScript, которая укажет на точную строку и столбец проблемы, так же как ошибка в коде.
Понимает ли редактор такие импорты?В VS Code или Cursor нужно установить расширение TypeScript 7 и указать ему установку TypeScript вашего проекта, затем подтвердить доверие к рабочей папке, чтобы оно могло использовать встроенный компилятор; Zed требует немного более ручной настройки.
Могу ли я импортировать файл JSON Schema?Напрямую через Motherload — нет: для файлов .schema.jsonc и .schema.json5 в README рекомендуется использовать отдельный пакет dotschema.
Какие есть похожие проекты?reylo, vanilla-extract, nx, html-webpack-plugin, react-grab, linaria, oxc, liteparse
В каких он темах?dotenv, jest, type-safe, config, webpack, data, csv, parser, build-tool, yaml, bun, vite
Автор
colinhacks
Размер
1.9 MB
Звёзды
319
Возраст
1 мес
Коммиты · 90 дней