TypeScript types for Enonic XP
Note There now exists official TypeScript-types from Enonic.
This library will now work as a proxy the official types – where they exist. Its new purpose will be to provide types
for all the libraries that doesn't have official support yet.
Installing individual packages
You can install individual packages with support for Enonic libraries like this:
You can find the complete list of supported packages on npm.
npm i --save-dev @item-enonic-types/core
npm i --save-dev @item-enonic-types/global
npm i --save-dev @item-enonic-types/lib-menu
Installing all packages
It is also possible to install all packages by installing enonic-types like this:
npm i --save-dev enonic-types
Update tsconfig.json
We recommend using webpack-starter as the base of your XP-project.
To add the TypeScript-types you need to update your tsconfig.json with the following:
{
"compilerOptions": {
"target": "es5",
"strict": true,
"sourceMap": true,
"allowJs": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"module": "commonjs",
"moduleResolution": "node",
"types": ["node", "@item-enonic-types/global"],
"rootDirs": [
"./src/main/resources",
"./.xp-codegen"
],
"paths": {
"/lib/xp/*": ["./node_modules/@enonic-types/lib-*"],
"/lib/*": [ "./node_modules/@item-enonic-types/lib-*" ,"./src/main/resources/lib/*"],
"/site/*": ["./.xp-codegen/site/*"]
}
},
"include": [
"./.xp-codegen/**/*",
"./src/main/resources/**/*"
],
"exclude": ["./build/*"]
}
Note that individual packages that are not directly under "/lib/..."
needs to be mapped separately.
An example is Freemarker:
{
"compilerOptions": {
"paths": {
+ "/lib/tineikt/freemarker": ["./node_modules/@item-enonic-types/lib-freemarker"]
}
}
}
Code generation
We recommend using this library together with the xp-codegen-plugin Gradle plugin. xp-codegen-plugin will create TypeScript interfaces
for your content-types. Those interfaces will be very useful together with this library.
Example
We have an Enonic service that returns an article by id.
import type { Article } from "../../site/content-types";
import { get as getOne, type Content } from "/lib/xp/content";
export function get(req: XP.Request): XP.Response {
const content = getOne<Content<Article>>({
key: req.params.id!
});
if (content !== null) {
const article: Article = content.data;
return {
status: 200,
body: article
}
} else {
return {
status: 404
};
}
}
- We import an
interface Article { ... }
generated by xp-codegen-plugin. - The standard XP-libraries are mapped to their paths by the change to tsconfig.json.
- We use
XP.Request
and XP.Response
to control the shape of our controller. content
is of the type Content<Article> | null
, so we have to do a null check before proceeding.
Supported libraries