const { compile } = require('@riotjs/compiler') const { Transformer } = require('@parcel/plugin') const SourceMap = require('@parcel/source-map').default const { relative } = require('path') /** * Generate the hmr code depending on the tag generated by the compiler * @param {string} path - path to the component file * @returns {string} the code needed to handle the riot hot reload */ function hotReload(path) { return `;(() => { if (module.hot) { const hotReload = require('@riotjs/hot-reload').default module.hot.accept() if (module.hot.data) { const component = require('./${path}').default; hotReload(component) } } })()` } module.exports = new Transformer({ async loadConfig({config}) { const riotConfig = await config.getConfig( ['.riotrc', '.riotrc.js', 'riot.config.js'], { packageKey: 'riot' } ) return riotConfig?.contents ?? {} }, async transform({asset, config, options}) { const source = await asset.getCode() const sourceMap = new SourceMap(options.projectRoot) const {code, map} = compile(source, { file: asset.filePath, ...config }) asset.type = 'js' asset.setCode(`${code}${config?.hot ? hotReload(relative(options.projectRoot, asset.filePath)) : ''}`) asset.setMap(sourceMap.addVLQMap(map)) return [asset] } })