Skip to navigation Skip to main content
Eleventy
Eleventy Documentation
Stable
3.0.0
Canary
3.0.1-alpha.1
Toggle Menu
Eleventy 1.93s
Astro 22.90s

编程式 API

Contents

You can run Eleventy in any arbitrary Node script.

写入文件系统

别忘了先将 Eleventy 安装项目本地

接下来创建一个名为 my-node-script.js、内容如下的文件:

my-node-script.js
import Eleventy from "@11ty/eleventy";

let elev = new Eleventy();
await elev.write();
(async function () {
const { Eleventy } = await import("@11ty/eleventy");

let elev = new Eleventy();
await elev.write();
})();

然后从命令行运行这个新脚本。 运行此脚本时不用输入 ~ $ 字样。

node my-node-script.js

不写入文件系统

调用 .write() 函数会将输出写入到文件系统中。如果你希望以编程方式获取出输出内容而不写入文件系统的话,请使用 .toJSON().toNDJSON() 函数。

JSON 格式的输出

my-node-script.js
import Eleventy from "@11ty/eleventy";

let elev = new Eleventy();
let json = await elev.toJSON();

// All results
console.log(json);
(async function () {
const { Eleventy } = await import("@11ty/eleventy");

let elev = new Eleventy();
let json = await elev.toJSON();

// All results
console.log(json);
})();

ndjson Output

my-node-script.js
import Eleventy from "@11ty/eleventy";

let elev = new Eleventy();
let stream = await elev.toNDJSON();
stream.on("data", (entry) => {
// Stream one output result at a time
let json = JSON.parse(entry.toString());
console.log(json);
});
(async function () {
const { Eleventy } = await import("@11ty/eleventy");

let elev = new Eleventy();
let stream = await elev.toNDJSON();
stream.on("data", (entry) => {
// Stream one output result at a time
let json = JSON.parse(entry.toString());
console.log(json);
});
})();

更改输入和输出目录

第一个参数代表的是输入目录,第二个参数代表的是输出目录。

my-node-script.js
import Eleventy from "@11ty/eleventy";

let elev = new Eleventy(".", "_site");

// Use `write` or `toJSON` or `toNDJSON`
(async function () {
const { Eleventy } = await import("@11ty/eleventy");

let elev = new Eleventy(".", "_site");

// Use `write` or `toJSON` or `toNDJSON`
})();

完整的参数列表

Eleventy 函数的第三个参数是一个对象(object)类型。

(此部分文档仍在编写中,但欢迎你进入 Eleventy v3.0.0 版本的源码探险,深入了解 Eleventy 的内部原理)

my-node-script.js
import Eleventy from "@11ty/eleventy";

let elev = new Eleventy(".", "_site", {
// --quiet
quietMode: true,

// --config
configPath: ".eleventy.js",

config: function (eleventyConfig) {
// Do some custom Configuration API stuff
// Works great with eleventyConfig.addGlobalData
},
});

// Use `write` or `toJSON` or `toNDJSON`
(async function () {
const { Eleventy } = await import("@11ty/eleventy");

let elev = new Eleventy(".", "_site", {
// --quiet
quietMode: true,

// --config
configPath: ".eleventy.js",

config: function (eleventyConfig) {
// Do some custom Configuration API stuff
// Works great with eleventyConfig.addGlobalData
},
});

// Use `write` or `toJSON` or `toNDJSON`
})();

Other pages in Eleventy Projects: