chore: refactored build script to wrap in immediately invoked function
ae4bd5c8
1 file(s) · +28 −4
| 68 | 68 | ||
| 69 | 69 | if (componentStartIndex > 0) { |
|
| 70 | 70 | // Dependencies are at the top (before the component class) |
|
| 71 | - | const dependencies = lines.slice(0, componentStartIndex).join("\n"); |
|
| 72 | - | const componentCode = lines.slice(componentStartIndex).join("\n"); |
|
| 71 | + | let dependencies = lines.slice(0, componentStartIndex).join("\n"); |
|
| 72 | + | let componentCode = lines.slice(componentStartIndex).join("\n"); |
|
| 73 | 73 | ||
| 74 | - | // Create new content with component first, then dependencies |
|
| 74 | + | // Replace 'var' with 'const' in dependencies to prevent hoisting issues |
|
| 75 | + | // This ensures variables are not hoisted as undefined when code is reorganized |
|
| 76 | + | dependencies = dependencies.replace(/\bvar\s+/g, "const "); |
|
| 77 | + | ||
| 78 | + | // Find and extract the customElements.define() call |
|
| 79 | + | const defineRegex = /customElements\.define\([^)]+\);?\n?/; |
|
| 80 | + | const defineMatch = componentCode.match(defineRegex); |
|
| 81 | + | let defineCall = ""; |
|
| 82 | + | ||
| 83 | + | if (defineMatch) { |
|
| 84 | + | defineCall = defineMatch[0]; |
|
| 85 | + | // Remove the define call from component code |
|
| 86 | + | componentCode = componentCode.replace(defineRegex, ""); |
|
| 87 | + | } |
|
| 88 | + | ||
| 89 | + | // Create new content wrapped in IIFE to avoid global namespace pollution |
|
| 75 | 90 | const newContent = `// User-editable ${componentName} component |
|
| 76 | 91 | // @noble/hashes are bundled at the bottom of this file |
|
| 77 | 92 | ||
| 93 | + | (function() { |
|
| 94 | + | // ========================================== |
|
| 95 | + | // COMPONENT CODE |
|
| 96 | + | // ========================================== |
|
| 97 | + | ||
| 78 | 98 | ${componentCode} |
|
| 79 | 99 | ||
| 80 | 100 | // ========================================== |
|
| 81 | 101 | // BUNDLED DEPENDENCIES BELOW |
|
| 82 | 102 | // ========================================== |
|
| 83 | 103 | ||
| 84 | - | ${dependencies}`; |
|
| 104 | + | ${dependencies} |
|
| 105 | + | ||
| 106 | + | // Register custom element after dependencies are loaded |
|
| 107 | + | ${defineCall} |
|
| 108 | + | })();`; |
|
| 85 | 109 | ||
| 86 | 110 | await writeFile( |
|
| 87 | 111 | `dist/components/${componentName}.js`, |