Guides Module System
Import an XML file
Bun natively supports .xml imports.
<?xml version="1.0" encoding="UTF-8"?>
<config env="production">
<database host="localhost" port="5432" name="myapp"/>
<server port="3000" timeout="30"/>
<feature name="auth"/>
<feature name="rateLimit"/>
</config>Import the file like any other source file. The module is the parsed document: one key for the root element, "@name" keys for attributes, arrays for repeated elements, and every value a string.
import doc from "./config.xml";
doc.config["@env"]; // => "production"
doc.config.database["@host"]; // => "localhost"
doc.config.server["@port"]; // => "3000"
doc.config.feature.map(f => f["@name"]); // => ["auth", "rateLimit"]The root element is also available as a named import:
import { config } from "./config.xml";
console.log(config.database["@name"]); // => "myapp"
console.log(Number(config.server["@timeout"])); // => 30For parsing XML strings at runtime, use Bun.XML.parse():
const data = Bun.XML.parse(`
<user id="7">
<name>John Doe</name>
<hobby>reading</hobby>
<hobby>coding</hobby>
</user>
`);
console.log(data.user.name); // => "John Doe"
console.log(data.user.hobby); // => ["reading", "coding"]
console.log(data.user["@id"]); // => "7"See XML for the rest of Bun's XML support, including the ordered { compact: false } node tree and Bun.XML.stringify().