Skip to content

Commit

Permalink
Update loader for Node 17
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Oct 21, 2021
1 parent a7c26fc commit 84308d1
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions test/loader.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,51 @@
import {promises as fs} from 'node:fs'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {transformSync} from 'esbuild'
import {URL, fileURLToPath} from 'node:url'
import {transform, transformSync} from 'esbuild'

const {getFormat, transformSource} = createLoader()
const {load, getFormat, transformSource} = createLoader()

export {getFormat, transformSource}
export {load, getFormat, transformSource}

/**
* A tiny JSX loader.
*/
export function createLoader() {
return {getFormat, transformSource}
return {load, getFormat, transformSource}

// Node version 17.
/**
* @param {string} url
* @param {unknown} context
* @param {Function} defaultLoad
*/
async function load(url, context, defaultLoad) {
if (path.extname(url) !== '.jsx') {
return defaultLoad(url, context, defaultLoad)
}

const fp = fileURLToPath(new URL(url))
const value = await fs.readFile(fp)

const {code, warnings} = await transform(String(value), {
sourcefile: fp,
sourcemap: 'both',
loader: 'jsx',
target: 'esnext',
format: 'esm'
})

if (warnings && warnings.length > 0) {
for (const warning of warnings) {
console.log(warning.location)
console.log(warning.text)
}
}

return {format: 'module', source: code}
}

// Pre version 17.
/**
* @param {string} url
* @param {unknown} context
Expand Down

0 comments on commit 84308d1

Please sign in to comment.