64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
const { compile } = require('@riotjs/compiler')
|
|
const { Transformer } = require('@parcel/plugin')
|
|
const SourceMap = require('@parcel/source-map').default
|
|
const { basename } = require('path')
|
|
|
|
const CONFIG_FILES = ['.riotrc', '.riotrc.js', 'riot.config.js']
|
|
const PACKAGE_KEY = 'riot'
|
|
|
|
/**
|
|
* 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(
|
|
CONFIG_FILES,
|
|
{
|
|
packageKey: PACKAGE_KEY
|
|
}
|
|
)
|
|
const shouldInvalidateOnStartup = riotConfig &&
|
|
riotConfig?.filePath?.endsWith('.js') ||
|
|
riotConfig?.filePath?.endsWith(CONFIG_FILES[0])
|
|
|
|
if (shouldInvalidateOnStartup) {
|
|
config.invalidateOnStartup()
|
|
}
|
|
|
|
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
|
|
})
|
|
|
|
// the suffix will be added only for the HMR
|
|
const suffix = config?.hot ? hotReload(basename(asset.filePath)) : ''
|
|
|
|
asset.type = 'js'
|
|
asset.setCode(`${code}${suffix}`)
|
|
asset.setMap(sourceMap.addVLQMap(map))
|
|
|
|
return [asset]
|
|
}
|
|
})
|