温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/docs/runtime/toml
点击访问原文链接
TOML - BunDocumentation Index

Fetch the complete documentation index at: /docs/llms.txt

Use this file to discover all available pages before exploring further.

Skip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationUtilitiesTOMLRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this pageRuntime APIBun.TOML.parse()Supported TOML FeaturesError HandlingModule ImportES ModulesDefault ImportNamed ImportsImport AttributesCommonJSHot Reloading with TOMLBundler IntegrationDynamic ImportsUtilitiesTOMLCopy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">*]:[overflow-wrap:anywhere]">

Use Bun’s built-in support for TOML files through both runtime APIs and bundler integration

Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">In Bun, TOML is a first-class citizen alongside JSON, JSON5, and YAML. You can: Parse TOML strings with Bun.TOML.parse import & require TOML files as modules at runtime (including hot reloading & watch mode support) import & require TOML files in frontend apps via Bun’s bundler ​Runtime API ​Bun.TOML.parse() Parse a TOML string into a JavaScript object.
import { TOML } from "bun";
const text = `
name = "my-app"
version = "1.0.0"
debug = true

[database]
host = "localhost"
port = 5432

[features]
tags = ["web", "api"]
`;

const data = TOML.parse(text);
console.log(data);
// {
// name: "my-app",
// version: "1.0.0",
// debug: true,
// database: { host: "localhost", port: 5432 },
// features: { tags: ["web", "api"] }
// }
​Supported TOML Features Bun’s TOML parser supports the TOML v1.0 specification, including: Strings: basic ("...") and literal ('...'), including multi-line Integers: decimal, hex (0x), octal (0o), and binary (0b) Floats: including inf and nan Booleans: true and false Arrays: including mixed types and nested arrays Tables: standard ([table]) and inline ({ key = "value" }) Array of tables: [[array]] Dotted keys: a.b.c = "value" Comments: using #
const data = Bun.TOML.parse(`
# Application config
title = "My App"

[owner]
name = "John Doe"

[database]
enabled = true
ports = [8000, 8001, 8002]
connection_max = 5000

[servers.alpha]
ip = "10.0.0.1"
role = "frontend"

[servers.beta]
ip = "10.0.0.2"
role = "backend"
`);
​Error Handling Bun.TOML.parse() throws if the TOML is invalid:
try {
Bun.TOML.parse("invalid = = =");
} catch (error) {
console.error("Failed to parse TOML:", error.message);
}
​Module Import ​ES Modules You can import TOML files directly as ES modules. The TOML content is parsed and made available as both default and named exports: config.toml
[database]
host = "localhost"
port = 5432
name = "myapp"

[redis]
host = "localhost"
port = 6379

[features]
auth = true
rateLimit = true
analytics = false
​Default Import app.ts
import config from "./config.toml";

console.log(config.database.host); // "localhost"
console.log(config.redis.port); // 6379
​Named Imports You can destructure top-level TOML tables as named imports: app.ts
import { database, redis, features } from "./config.toml";

console.log(database.host); // "localhost"
console.log(redis.port); // 6379
console.log(features.auth); // true
Or combine both: app.ts
import config, { database, features } from "./config.toml";

// Use the full config object
console.log(config);

// Or use specific parts
if (features.rateLimit) {
setupRateLimiting(database);
}
​Import Attributes You can also use import attributes to load any file as TOML: app.ts
import myConfig from "./my.config" with { type: "toml" };
​CommonJS TOML files can also be required in CommonJS: app.ts
const config = require("./config.toml");
console.log(config.database.name); // "myapp"

// Destructuring also works
const { database, redis } = require("./config.toml");
console.log(database.port); // 5432
​Hot Reloading with TOML When you run your application with bun --hot, changes to TOML files are automatically detected and reloaded without restarting: config.toml
[server]
port = 3000
host = "localhost"

[features]
debug = true
verbose = false
server.ts
import { server, features } from "./config.toml";

console.log(`Starting server on ${server.host}:${server.port}`);

Bun.serve({
port: server.port,
hostname: server.host,
fetch(req) {
if (features.verbose) {
console.log(`${req.method} ${req.url}`);
}
return new Response("Hello World");
},
});
Run with hot reloading: terminal
bun --hot server.ts
Now when you modify config.toml, the changes are immediately reflected in your running application. ​Bundler Integration When you import TOML files and bundle with Bun, the TOML is parsed at build time and included as a JavaScript module: terminal
bun build app.ts --outdir=dist
This means: Zero runtime TOML parsing overhead in production Smaller bundle sizes Tree-shaking support for unused properties (named imports) ​Dynamic Imports TOML files can be dynamically imported:
const config = await import("./config.toml");

Was this page helpful?

YesNoSuggest editsRaise issueConsolePreviousYAMLNext⌘IxgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform

TOML - Bun,AI智能索引,全网链接索引,智能导航,网页索引

    Use Bun