* Convert ES Module syntax to CommonJS
(content, moduleName)
| 59 | * Convert ES Module syntax to CommonJS |
| 60 | */ |
| 61 | function convertToCommonJS(content, moduleName) { |
| 62 | // Handle different module types |
| 63 | if (moduleName === 'node') { |
| 64 | // node.js already uses CommonJS, just copy it |
| 65 | return content; |
| 66 | } |
| 67 | |
| 68 | if (moduleName === 'web') { |
| 69 | // Web module doesn't need CommonJS |
| 70 | return content; |
| 71 | } |
| 72 | |
| 73 | // For index.js (bundler), convert import/export to require/module.exports |
| 74 | let cjs = content |
| 75 | // Convert: import ... from '../wasm/...' |
| 76 | .replace(/import\s+(\w+|\{[^}]+\}|\*\s+as\s+\w+)\s+from\s+['"]([^'"]+)['"]/g, |
| 77 | (match, imports, path) => { |
| 78 | if (imports.startsWith('*')) { |
| 79 | const varName = imports.match(/\*\s+as\s+(\w+)/)[1]; |
| 80 | return `const ${varName} = require('${path}')`; |
| 81 | } else if (imports.startsWith('{')) { |
| 82 | return `const ${imports} = require('${path}')`; |
| 83 | } else { |
| 84 | return `const ${imports} = require('${path}')`; |
| 85 | } |
| 86 | }) |
| 87 | // Convert: export class/function |
| 88 | .replace(/export\s+(class|function|const|let|var)\s+(\w+)/g, '$1 $2') |
| 89 | // Convert: export default |
| 90 | .replace(/export\s+default\s+/g, 'module.exports = ') |
| 91 | // Convert: export { ... } |
| 92 | .replace(/export\s*\{([^}]+)\}/g, (match, exports) => { |
| 93 | const items = exports.split(',').map(e => e.trim()); |
| 94 | return `module.exports = { ${items.join(', ')} }`; |
| 95 | }); |
| 96 | |
| 97 | return cjs; |
| 98 | } |