NOT STABLE, consider that when using it
Pre-evaluate code at build-time.
Inspired by babel-plugin-preval & forced by the behaviour of
next.js (in detail the getInitialProps
function on client side).
This small transformer came to live.
You need to do some dynamic stuff, but don't want to do it at runtime. Or maybe you want to do stuff like read the filesystem to get a list of files and you can't do that in the browser.
babel-plugin-preval#the-problem
This allows you to specify some code that gets transpiled, runs in Node and whatever
your run
function returns in there will be swapped. For example:
import { preval } from 'ts-transformer-preval-macro';
const data = preval`async function run() {
return 5+5;
}`;
becomes
const data = 10;
Something more fancy?
import IContentBlock from '../interfaces/IContentBlock';
import { preval } from 'ts-transformer-preval-macro';
const content: IContentBlock[] = preval`
import {FetchData, getContentPiece} from '../services/DataService';
import IContentBlock from '../interfaces/IContentBlock';
async function run() {
const fetcher = new FetchtData();
const contentBlocks: IContentBlock[] = getContentPiece<IContentBlock>(
await fetcher.getContentBlocks({
'fields.identifier[match]': 'article.'
})
);
return contentBlocks;
}`;
becomes
import IContentBlock from '../interfaces/IContentBlock';
const content: IContentBlock[] = [
{
identifier: 'article.typescript.transformer.preval',
title: 'How to write a typescript transformer',
content: '...',
slug: 'howto-write-a-typescript-transformer'
},
{
identifier: 'article.typescript.transformer.101',
title: 'Typescript transformer 101',
content: '...',
slug: 'typescript-transformer-101'
}
];
npm i ts-transformer-preval-macro
type: string
default: development
Switch basic settings between production
and development
.
type: boolean
default: false
If activated results of pre-evaluation will be cached until code is changed.
production
and development
mode have separated caches.
type: boolean
default: false
If activated evaluated code won't be deleted so you can run & inspect it manually.
{
loader: 'ts-loader',
options: {
getCustomTransformers: () => {
return {
before: [
prevalTransformer({
cacheActivated: true,
mode: isProduction ? 'prod' : 'dev',
debug: false,
})(),
],
};
}
}
}
- Don´t harvest any data ¯\_(ツ)_/¯
- Git flow
kentcdodds awesome babel-plugin-preval.
MIT