Pre-processors
You can pre-process your components contents using your favorite programming language.
The @riotjs/compiler
gives you the possibility to register your preprocessors:
import { registerPreprocessor } from '@riotjs/compiler'
import pug from 'pug'
import sass from 'node-sass'
import ts from 'typescript'
registerPreprocessor('template', 'pug', function(code, { options }) {
const { file } = options
console.log('Preprocess the template', file)
return {
code: pug.render(code),
// no sourcemap here
map: null
}
})
registerPreprocessor('css', 'sass', function(code, { options }) {
const { file } = options
console.log('Compile the sass code in', file)
const {css} = sass.renderSync({
data: code
})
return {
code: css.css.toString(),
map: null
}
})
registerPreprocessor('javascript', 'ts', function(code, { options }) {
const { file } = options
const result = ts.transpileModule(code, {
fileName: file,
compilerOptions: {
module: ts.ModuleKind.ESNext
}
})
return {
code: result.outputText,
map: null
}
})
The Riot.js preprocessors can be only of three types template
, css
, javascript
(the first argument of the registerPreprocessor
function).To compile your components with a different template engine you will need to specify the template
option via compiler:
import { compile } from '@riotjs/compiler'
compile(source, {
template: 'pug'
})
For the css
and javascript
preprocessors you can simply enable them directly in your components via type="{preprocessor}"
attribute
<my-component>
<p>{getMessage}</p>
<style type="scss">
import 'color/vars'
p {
color: $primary;
}
</style>
<script type="ts">
export default {
getMessage():string {
return 'hello world'
}
}
</script>
</my-component>
Pre-processors Caveats
The Riot.js compiler generates sourcempas out of the code provided by the pre-processors. If your preprocessor will not provide any map
output the compiler will not output proper sourcemaps.
import { registerPreprocessor } from '@riotjs/compiler'
import babel from '@babel/core'
registerPreprocessor('javascript', 'babel', function(code, { options }) {
// the babel.transform returns properly an object containing the keys {map, code}
return babel.transform(code, {
sourceMaps: true,
// notice that whitelines should be preserved
retainLines: true,
sourceFileName: options.file,
presets: [[
'@babel/env',
{
targets: {
edge: true
},
loose: true,
modules: false,
useBuiltIns: 'usage'
}
]]
})
})
registerPreprocessor('javascript', 'my-js-preprocessor', function(code, { options }) {
// the Riot.js compiler will not be able to generate sourcemaps
return {
code: myPreprocessor(code),
map: null
}
})
The javascript preprocessors should preserve the code whitelines of the original source code otherwise the resulting sourcemap will have a broken offset.