Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created November 13, 2023 05:17
Show Gist options
  • Save souporserious/778d5290362699ffb8901fb125dd7fde to your computer and use it in GitHub Desktop.
Save souporserious/778d5290362699ffb8901fb125dd7fde to your computer and use it in GitHub Desktop.
import * as webpack from 'webpack'
import { glob } from 'glob'
import { dirname, resolve } from 'node:path'
function getPathnameFromFilename(filename: string) {
return (
filename
// Remove file extensions
.replace(/\.[^/.]+$/, '')
// Remove leading "./"
.replace(/^\.\//, '')
// Remove leading sorting number
.replace(/\/\d+\./g, '/')
)
}
export default async function loader(
this: webpack.LoaderContext<{}>,
source: string | Buffer
) {
this.cacheable(false)
const callback = this.async()
if (
source.includes(`import { createSourceFiles } from 'mdxts'`) ||
source.includes(`import { createSourceFiles } from "mdxts"`)
) {
const match = /createSourceFiles\(([^)]+)\)/.exec(source.toString())
// TODO: get the context directory from the paths not the resource path
// const contextDirectory = dirname(this.resourcePath)
// this.addContextDependency(contextDirectory)
if (match) {
const globPattern = match[1].replace(/['"]/g, '') // Remove quotes from the pattern
const filePaths = await glob(globPattern, {
cwd: dirname(this.resourcePath),
})
const allImports = filePaths
.map((filePath) => {
const pathname = getPathnameFromFilename(
resolve(dirname(this.resourcePath), filePath).replace(
`${process.cwd()}/`,
''
)
)
return `"${pathname}": lazy(() => import('${filePath}'))`
})
.join(',\n')
// filePaths.forEach((file) =>
// this.addDependency(resolve(contextDirectory, file))
// )
source = `import { lazy } from 'react'\n${source}`
source = source
.toString()
.replace(
/createSourceFiles\(([^)]+)\)/,
`createSourceFiles({\n${allImports}\n})`
)
console.log(source)
callback(null, source)
} else {
callback(null, source)
}
} else {
callback(null, source)
}
}
// Example Usage
// config.module.rules.push({
// test: /\.(?:js|tsx?)$/,
// exclude: /node_modules/,
// use: ['mdxts/loader'],
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment