Skip to content

riot/compiler

Repository files navigation

Build Status Issue Count Coverage Status NPM version NPM downloads MIT License

Important

This compiler will not work with older Riot.js versions. It's designed to work with Riot.js > 4.0.0. For Riot.js < 4.0.0 please check thev3branch

Installation

npm i @riotjs/compiler -D

Usage

The riot compiler can compile only strings:

import{compile}from'@riotjs/compiler'

const{code,map}=compile('<p>{hello}</p>')

You can compile your tags also using the newregisterPreprocessorandregisterPostprocessorAPIs for example:

import{
compiler,
registerPreprocessor,
registerPostprocessor,
}from'@riotjs/compiler'
importpugfrom'pug'
import*asbabelfrom'@babel/core'

// process your tag template before it will be compiled
registerPreprocessor('template','pug',function(code,{options}){
const{file}=options
console.log('your file path is:',file)

return{
code:pug.render(code),
// no sourcemap here
map:null,
}
})

// your compiler output will pass from here
registerPostprocessor(function(code,{options}){
const{file}=options
console.log('your file path is:',file)

// notice that babel.transformSync returns {code, map}
returnbabel.transformSync(code)
})

const{code,map}=compile('<p>{hello}</p>',{
// specify the template preprocessor
template:'pug',
})

API

compile(string, options)

@returns{ code, map }output that can be used by Riot.js

  • string:is your tag source code
  • options:the options should contain thefilekey identifying the source of the string to compile and thetemplatepreprocessor to use as string

Note: specific preprocessors like thecssor thejavascriptones can be enabled simply specifying thetypeattribute in the tag source code for example

<my-tag>
<styletype= "scss">
//...
</style>
</my-tag>

registerPreprocessor(type, id, preprocessorFn)

@returnsObjectcontaining all the preprocessors registered

  • type:either one oftemplatecssorjavascript
  • id:unique preprocessor identifier
  • preprocessorFn:function receiving the code as first argument and the current options as second

registerPostprocessor(postprocessorFn)

@returnsSetcontaining all the postprocessors registered

  • postprocessorFn:function receiving the compiler output as first argument and the current options as second

generateTemplateFunctionFromString(string, parserOptions)

@returnsstringwith the code to execute the @riotjs/bindingstemplatefunction

generateSlotsFromString(string, parserOptions)

@returnsstringwith the code to generate components slots in runtime