ts-transformer-preval-macro
v0.0.5
Published
Pre-evaluate code at build-time
Downloads
3
Maintainers
Readme
ts-transformer-preval
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.
The problem
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
The solution
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'
}
];
Install
npm i ts-transformer-preval-macro
Configuration
mode
type: string
default: development
Switch basic settings between production
and development
.
cacheActivated
type: boolean
default: false
If activated results of pre-evaluation will be cached until code is changed.
production
and development
mode have separated caches.
debug
type: boolean
default: false
If activated evaluated code won't be deleted so you can run & inspect it manually.
Usage
With loaders
With ts-loader
{
loader: 'ts-loader',
options: {
getCustomTransformers: () => {
return {
before: [
prevalTransformer({
cacheActivated: true,
mode: isProduction ? 'prod' : 'dev',
debug: false,
})(),
],
};
}
}
}
With atl
With tsc
Contribute
- Don´t harvest any data ¯\_(ツ)_/¯
- Git flow
Inspired by
kentcdodds awesome babel-plugin-preval.
LICENSE
MIT