|
| 1 | +/* eslint-disable no-shadow */ |
| 2 | +/* eslint-disable @typescript-eslint/no-var-requires */ |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const { Parser } = require('acorn'); |
| 6 | +const { walk } = require('svelte/compiler'); |
| 7 | +const MagicString = require('magic-string'); |
| 8 | + |
| 9 | +const parseDir = (dir) => { |
| 10 | + fs.readdir(dir, (err, children) => { |
| 11 | + if (err) return |
| 12 | + children.forEach((child) => { |
| 13 | + const pathname = `${dir}/${child}`; |
| 14 | + fs.lstat(pathname, (err, stats) => { |
| 15 | + if (err) return |
| 16 | + if (stats.isDirectory()) { |
| 17 | + parseDir(pathname); |
| 18 | + } |
| 19 | + if (stats.isFile()) { |
| 20 | + fs.readFile(pathname, 'utf-8', (err, content) => { |
| 21 | + if (err) return |
| 22 | + const ast = Parser.parse(content, { |
| 23 | + ecmaVersion: 'latest', |
| 24 | + sourceType: 'module' |
| 25 | + }); |
| 26 | + const magicContent = new MagicString(content); |
| 27 | + walk(ast, { |
| 28 | + enter(node) { |
| 29 | + if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.source) { |
| 30 | + const filename = path.resolve(path.dirname(pathname), `${node.source.value}.js`); |
| 31 | + const dirIndex = path.resolve(path.dirname(pathname), `${node.source.value}/index.js`); |
| 32 | + if (fs.existsSync(filename)) { |
| 33 | + magicContent.prependLeft(node.source.end - 1, '.mjs'); |
| 34 | + } else if (fs.existsSync(dirIndex)) { |
| 35 | + magicContent.prependLeft(node.source.end - 1, '/index.mjs'); |
| 36 | + } |
| 37 | + } else if ( |
| 38 | + node.type === 'ExportDefaultDeclaration' |
| 39 | + && node.declaration?.left?.type === 'MemberExpression' |
| 40 | + && node.declaration.left.object.name === 'module' |
| 41 | + && node.declaration.left.property.name === 'exports' |
| 42 | + ) { |
| 43 | + magicContent.remove(node.declaration.left.start, node.declaration.right.start); |
| 44 | + } |
| 45 | + } |
| 46 | + }); |
| 47 | + const mjsPathname = pathname.replace('/esm', '').replace('.js', '.mjs'); |
| 48 | + fs.writeFile(mjsPathname, magicContent.toString(), (err) => { |
| 49 | + if (err) throw err; |
| 50 | + }); |
| 51 | + }); |
| 52 | + } |
| 53 | + }); |
| 54 | + }); |
| 55 | + }); |
| 56 | +} |
| 57 | + |
| 58 | +parseDir('./dist/esm'); |
0 commit comments