@eggjs/view

中文文档
4.1.0发布于 2026/10/07MITTypeScriptES Module构建来源已验证近 30 天下载 4700

Base view plugin for egg

原始使用文档
文档目录15 节
  1. Install
  2. Usage
  3. Use a template engine
  4. Use multiple view engine
  5. How to write a view plugin
  6. View engine
  7. Register
  8. Configure
  9. Configuration
  10. Root
  11. defaultExtension
  12. viewEngine and defaultViewEngine
  13. Questions & Suggestions
  14. License
  15. Contributors

@eggjs/view

NPM version NPM download Node.js Version PRs Welcome CodeRabbit Pull Request Reviews

Base view plugin for egg

it's a plugin that has been built-in for egg.

Install

npm i @eggjs/view

Usage

// {app_root}/config/plugin.ts
export default {
  view: {
    enable: true,
    package: '@eggjs/view',
  },
};

Use a template engine

@eggjs/view don't have build-in view engine, So you should choose a template engine like ejs, and install egg-view-ejs plugin.

You can choose a template engine first, link ejs, so we use egg-view-ejs plugin.

egg-view is in eggjs, so you just need configure egg-view-ejs.

// config/plugin.ts
export default {
  ejs: {
    enable: true,
    package: 'egg-view-ejs',
  },
};

Configure the mapping, the file with .ejs extension will be rendered by ejs.

// config/config.default.ts
export default {
  view: {
    mapping: {
      '.ejs': 'ejs',
    },
  },
};

In controller, you can call ctx.render.

export default (app: Application) => {
  return class UserController extends app.Controller {
    async list() {
      const { ctx } = this;
      await ctx.render('user.ejs');
    }
  };
}

If you call ctx.renderString, you should specify viewEngine in viewOptions.

export default (app: Application) => {
  return class UserController extends app.Controller {
    async list() {
      const { ctx } = this;
      ctx.body = await ctx.renderString(
        '<%= user %>',
        { user: 'popomore' },
        {
          viewEngine: 'ejs',
        }
      );
    }
  };
}

Use multiple view engine

[egg-view] support multiple view engine, so you can use more than one template engine in one application.

If you want add another template engine like nunjucks, then you can add egg-view-nunjucks plugin.

Configure the plugin and mapping

// config/plugin.ts
export default {
  ejs: {
    enable: true,
    package: 'egg-view-ejs',
  },
  nunjucks: {
    enable: true,
    package: 'egg-view-nunjucks',
  },
};
// config/config.default.ts
export default {
  view: {
    mapping: {
      '.ejs': 'ejs',
      '.nj': 'nunjucks',
    },
  },
};

You can simply render the file with .nj extension.

await ctx.render('user.nj');

How to write a view plugin

You can use @eggjs/view's API to register a plugin.

View engine

Create a view engine class first, and implement render and renderString, if the template engine don't support, just throw an error. The view engine is context level, so it receive ctx in constructor.

// lib/view.ts
export default class MyView {
  constructor(ctx) {
    // do some initialize
    // get the plugin config from `ctx.app.config`
  }

  async render(fullpath: string, locals: Record<string, any>) {
    return myengine.render(fullpath, locals);
  }

  async renderString() {
    throw new Error('not implement');
  }
}

render and renderString support generator function, async function, or normal function return a promise.

If the template engine only support callback, you can wrap it by Promise.

class MyView {
  render(fullpath, locals) {
    return new Promise((resolve, reject) => {
      myengine.render(fullpath, locals, (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    });
  }
}

These methods receive three arguments, renderString will pass tpl as the first argument instead of name in render.

render(name, locals, viewOptions)

  • name: the file path that can resolve from root (app/view by default)
  • locals: data used by template
  • viewOptions: the view options for each render, it can override the view default config in config/config.default.js. Plugin should implement it if it has config. When you implement view engine, you will receive this options from render, the options contain:
    • root: egg-view will resolve the name to full path, but seperating root and name in viewOptions.
    • name: the original name when call render
    • locals: the original locals when call render

renderString(tpl, locals, viewOptions)

  • tpl: the template string instead of the file, using in renderString
  • locals: same as render
  • viewOptions: same as render

Register

After define a view engine, you can register it.

// app.ts
import type { Application } from 'egg';
import MyView from './lib/view';

export default (app: Application) => {
  app.view.use('myName', MyView);
}

You can define a view engine name, normally it's a template name.

Configure

Define plugin name and depend on @eggjs/view

{
  "eggPlugin": {
    "name": "myName",
    "dependencies": ["view"]
  }
}

Set default config in config/config.default.ts, the name is equals to plugin name.

export default {
  myName: {},
};

See some examples

Configuration

Root

Root is ${baseDir}/app/view by default, but you can define multiple directory, seperated by ,. @eggjs/view will find a file from all root directories.

export default (appInfo: EggAppInfo) => {
  const baseDir = appInfo.baseDir;
  return {
    view: {
      root: `${baseDir}/app/view,${baseDir}/app/view2`,
    },
  };
}

defaultExtension

When render a file, you should specify a extension that let @eggjs/view know whitch engine you want to use. However you can define defaultExtension without write the extension.

// config/config.default.ts
export default {
  view: {
    defaultExtension: '.html',
  },
};

// controller
export default (app: Application) => {
  return class UserController extends app.Controller {
    async list() {
      const { ctx } = this;
      // render user.html
      await ctx.render('user');
    }
  }
}

viewEngine and defaultViewEngine

If you are using renderString, you should specify viewEngine in view config, see example above.

However, you can define defaultViewEngine without set each time.

// config/config.default.ts
export default {
  view: {
    defaultViewEngine: 'ejs',
  },
};

see config/config.default.ts for more detail.

Questions & Suggestions

Please open an issue here.

License

MIT

Contributors

Contributors

Made with contributors-img.

版本与发布记录

@eggjs/view 共发布 53 个版本,首次发布于 2025/02/04;过去 12 个月发布了 33 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.0latest2026/10/071 个月前
4.0.22026/10/061 个月前
4.0.2-rc.1rc2026/10/061 个月前
4.0.2-rc.02026/09/231 个月前
4.0.2-beta.27beta2026/09/201 个月前
4.0.2-beta.262026/08/073 个月前

关于 @eggjs/view 的常见问题

@eggjs/view 是什么?

Base view plugin for egg

如何安装 @eggjs/view?

在项目目录运行 npm install @eggjs/view,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:egg(4.2.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@eggjs/view 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@eggjs/view 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@eggjs/view 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.18.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@eggjs/view 可以商用吗?

@eggjs/view 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@eggjs/view 的下载量有多少?

根据 npm 官方下载统计,@eggjs/view 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,700 次,日均约 157 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@eggjs/view 还在维护吗?

最新版本 4.1.0 发布于 2026/10/07(1 个月前);至今共发布 53 个版本,其中过去 12 个月发布了 33 个;首次发布于 2025/02/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。