Improved code completion for JavaScript in XP with enonic-ts-codegen

Hi dear Enonic-friends!

If you are writing JavaScript-code for XP, this might be very useful for you!

I just remembered that is that TypeScript interfaces can be used in JsDoc!

This means that the enonic-ts-codegen library that we (at Item) created, can be super useful for JavaScript XP-projects (and not just TypeScript-projects).

It generates TypeScript files with interfaces for the xml-files you have in your XP-project.

Example:

Lets say you have the following content type file article.xml:

<?xml version="1.0" encoding="UTF-8"?>
<content-type>
  <display-name>Article</display-name>
  <super-type>base:structured</super-type>
  <form>
    <input name="title" type="TextLine">
      <label>Title of the article</label>
      <occurrences minimum="1" maximum="1"/>
    </input>

    <input name="body" type="HtmlArea">
      <label>Main text body</label>
      <occurrences minimum="0" maximum="1"/>
    </input>
  </form>
</content-type>

This will generate the following TypeScript-file article.ts:

export interface Article {
  /** Title of the article */
  title: string;
 
  /** Main text body */
  body?: string;
}

This is the shape of the json for that content type.

In JavaScript, we can then just use JsDoc to say that some data or has that shape, and get code completion (I’ve used IntelliJ in this example).

code%20completion

And the best part is that if you change your content-type xml, the interface is re-generated, so you get a tight coupling between the xml- and the js-files.

3 Likes

If anybody tries this out I would love some feedback.

Would it make any difference if the generated files are *.d.ts instead of *.ts?

Hi @tom!

First of all, thanks a lot for your effort - this looks like a great and helpful tool.

*.d.ts is preferred format for type definitions in Typescript, so it would be nice to have an option to generate files with this extension.

1 Like

Very good Alan!

I will test a bit around this, and I expect that *.d.ts is a better default file ending, as the generated files only contains type definitions.

I would recommend everyone coding in JavaScript to try out TypeScript for Enonic XP 7! :wink:

Use the webpack-starter and install the enonic-ts-codegen and enonic-types libraries.