@amisa/style-plugin
Version:
Transfom css's file to java scripts style element and js to script element
44 lines (40 loc) • 1.34 kB
text/typescript
const regex = /=\s*amisa.amisaCreateScriptElement\(['|"].*\.js['|"]\)/g
export function AmisaJsTransformScriptPlugin() {
const config = {
name: 'amisa-js-plugin', // Name of the plugin
transform(code: string, id: string): string | void | null | undefined {
let m
if (!id.includes('/dist/') && (m = regex.exec(code)) !== null) {
return replaceIt(m, code, id)
} else {
return code
}
}
}
return config
}
function replaceIt(m: RegExpExecArray, code: string, path: string) {
const jsFilePath = getJsFileName(m, path)
const jsContent = getJsContent(jsFilePath)
const amisaMethod = '';
const resultCode =
code.replace(regex, `= amisa.getAmisaScriptElement(\`${jsContent}\`);`) +
'\n\n' +
amisaMethod +
'\n\n'
return resultCode
}
document
function getJsFileName(m: RegExpExecArray, path: string) {
const finded = m[0]
const fileName = finded
.replace(/=\s*amisa.amisaCreateScriptElement\(['|"]\.\//, '')
.replace(/=\s*amisa.amisaCreateScriptElement\(['|"]/, '')
.replace(/["|']\)/, '')
const folder = require('path').dirname(path)
return require('path').resolve(folder, fileName)
}
function getJsContent(jsFilePath: string) {
const fileString = require('fs').readFileSync(jsFilePath).toString()
return fileString.replace(/\n\s*/g, ' ')
}