Skip to navigation Skip to main content
11ty Logo Sustainability Fundraising
Eleventy
Eleventy Documentation
Stable
2.0.1
Canary
3.0.0-alpha.16
Toggle Menu
Eleventy 5.81s
Remix 40.14s

编程式 API Added in v1.0.0

Contents

从 Eleventy 1.0 开始,你可以在自己的 Node 脚本中调用 Eleventy 了。 (这是 Eleventy Serverless 插件的幕后工作方式)

示例 Jump to heading

写入文件系统 Jump to heading

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

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

Filename my-node-script.js
const Eleventy = require("@11ty/eleventy");

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

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

node my-node-script.js

不写入文件系统 Jump to heading

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

JSON 格式的输出 Jump to heading

const Eleventy = require("@11ty/eleventy");

(async function () {
let elev = new Eleventy();
let json = await elev.toJSON();
// All results
console.log(json);
})();

ndjson 格式的输出 Jump to heading

const Eleventy = require("@11ty/eleventy");

(async function () {
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);
});
})();

更改输入和输出目录 Jump to heading

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

const Eleventy = require("@11ty/eleventy");

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

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

完整的参数列表 Jump to heading

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

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

const Eleventy = require("@11ty/eleventy");

(async function () {
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 Getting Started: