ejs-ts

1.0.0 • Public • Published

ejs-ts

Use TypeScript and type checking in your EJS templates!

Ejs-ts is a command-line utility that allows writing EJS templates with TypeScript type checking.

Please note that the whole utility uses awful RegExes to achieve the functionality. Take my apology if that causes any grief.

Install

npm install ejs-ts --save-dev

Usage

Create a TypeScript file describing the context of your EJS template:

// examples/context.ts
export interface User {
  firstName: string;
  lastName: string;
}
 
export interface Context {
  users: User[];
  currentDate: string;
}

Then create your template with .ets suffix. Prepend the EJS template with TypeScript defining your context like so:

// examples/users.ets
import { Context } from './context';
 
export default function({users, currentDate}: Context)
/* template */
User Report (<%- currentDate %>)
<users.forEach((user, i) => { -%>
#<%- i + 1 %> <%- user.firstName %> <%- user.lastName %>
<% }); -%>

Note that the /* template */ syntax separates your context code and the template code.

Now integrate ejs-ts into your build process:

# generate TypeScript from ETS templates 
npx ejs-ts gen-ts --in examples/
 
# compile TypeScript (replace with your own build) 
npx tsc examples/*.ts --target ES6 --module None
 
# generate EJS from compiled TypeScript 
npx ejs-ts gen-ejs --in examples/
 
# Clean up by-products of the process (optional) 
npx ejs-ts clean-up --in examples/
 
# execute JavaScript (replace with your execution) 
node examples/render.js
 

If you have any type issues or invalid typescript in the template, your compilation fails. You can examine the by-products to resolve the issue.

Feel free to explore the examples folder. You may also check out the repo and run test.sh to see the process in action. Maybe introduce an error to see the type checking in action.

Here is the example of generated EJS file:

User Report (<%- currentDate; %>)
<%
    users.forEach((user, i) => {
        ; -%>
#<%-
        i + 1; %> <%-
        user.firstName; %> <%-
        user.lastName; %>
<%
    });
    ; -%>

Tip: Set your Visual Studio Code to treat .ets files as .ejs to get syntax highlighting.

TODO

  • validate context passed to include calls

Readme

Keywords

Package Sidebar

Install

npm i ejs-ts

Weekly Downloads

89

Version

1.0.0

License

MIT

Unpacked Size

8.57 kB

Total Files

4

Last publish

Collaborators

  • zaber