Skip to content

Commit

Permalink
fix: module normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Jan 19, 2025
1 parent 33ec67d commit d7c8be8
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 42 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"@types/react": "^19.0.7",
"@types/react-dom": "^19.0.3",
"bunchee": "^6.3.2",
"codice": "^0.4.4",
"codice": "^0.5.0",
"devjar": "link:./",
"next": "^15.1.5",
"react": "^19.0.0",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 3 additions & 26 deletions site/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import FileTab from '../ui/file-tab'
const CDN_HOST = 'https://esm.sh'

const defaultFiles = {
'page.js': `\
'index.js': `\
import { useState } from 'react'
import Text from './mod1'
import Text from './text'
import './styles.css'
export default function App() {
Expand Down Expand Up @@ -68,7 +68,7 @@ const defaultFiles = {
}

export default function Page() {
const [activeFile, setActiveFile] = useState('page.js')
const [activeFile, setActiveFile] = useState('index.js')
const [files, setFiles] = useState(defaultFiles)
const [error, setError] = useState(null)

Expand All @@ -95,29 +95,6 @@ export default function Page() {
))}

<FileTab files={files} setFiles={setFiles} setActiveFile={setActiveFile} />
{/* <div
role="button"
className="filetab filetab--new"
>
<span
onClick={() => {
}}
>{`+`}</span>
<input
type='input'
onChange={(e) => {
const filename = e.target.value
// const modId = Object.keys(files).length
const newFilename = filename // './mod' + modId
setFiles({
...files,
[newFilename]: `export default function Mod${filename}() {}`,
})
setActiveFile(newFilename)
}}
/>
</div> */}
</div>
<Editor
highlight={highlight}
Expand Down
21 changes: 17 additions & 4 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { init, parse } from 'es-module-lexer'

let esModuleLexerInit
const isRelative = s => s.startsWith('./')
const removeExtension = (str: string) => str.replace(/\.[^/.]+$/, '')

function transformCode(_code, getModuleUrl, externals) {
const code = transform(_code, {
Expand Down Expand Up @@ -77,6 +78,7 @@ function replaceImports(source, getModuleUrl, externals) {
return code
}

// createRenderer is going to be stringified and executed in the iframe
function createRenderer(createModule_, getModuleUrl) {
let reactRoot

Expand Down Expand Up @@ -132,7 +134,7 @@ function createEsShimOptionsScript() {
return `\
window.esmsInitOptions = {
polyfillEnable: ['css-modules', 'json-modules'],
onerror: error => console.log(error),
onerror: console.error,
}`
}

Expand Down Expand Up @@ -240,11 +242,18 @@ function useLiveCode({ getModuleUrl }: { getModuleUrl?: (name: string) => string
* '@mod2': '...',
*/
const transformedFiles = Object.keys(files).reduce((res, filename) => {
const key = isRelative(filename) ? ('@' + filename.slice(2)) : filename
// 1. Remove ./
// 2. For non css files, remove extension
// e.g. './styles.css' -> '@styles.css'
// e.g. './foo.js' -> '@foo'
const moduleKey = isRelative(filename) ? ('@' + filename.slice(2)) : filename

if (filename.endsWith('.css')) {
res[key] = files[filename]
res[moduleKey] = files[filename]
} else {
res[key] = transformCode(files[filename], getModuleUrl, overrideExternals)
// JS or TS files
const normalizedModuleKey = removeExtension(moduleKey)
res[normalizedModuleKey] = transformCode(files[filename], getModuleUrl, overrideExternals)
}
return res
}, {})
Expand All @@ -259,6 +268,10 @@ function useLiveCode({ getModuleUrl }: { getModuleUrl?: (name: string) => string
// if render is not loaded yet, wait until it's loaded
script.onload = () => {
iframe.contentWindow.__render__(transformedFiles)
.catch((err) => {
setError(err)
})

}
}
}
Expand Down
14 changes: 8 additions & 6 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ declare global {
}
}

// importShim
function importShim(url: string): Promise<any>
}

async function createModule(files, { getModuleUrl }) {
let currentImportMap
let shim
async function createModule(
files: Record<string, string>,
{ getModuleUrl }: { getModuleUrl: (name: string) => string }
): Promise<void> {
let currentImportMap: HTMLScriptElement | undefined
let shim: any

async function setupImportMap() {
if (shim) return shim
Expand All @@ -26,7 +28,7 @@ async function createModule(files, { getModuleUrl }) {
await shim
}

function updateImportMap(imports) {
function updateImportMap(imports: Record<string, string>) {
imports['react'] = getModuleUrl('react')
imports['react-dom'] = getModuleUrl('react-dom')
imports['react-dom/client'] = getModuleUrl('react-dom/client')
Expand Down Expand Up @@ -57,7 +59,7 @@ async function createModule(files, { getModuleUrl }) {
)

updateImportMap(imports)
return self.importShim('index.js')
return self.importShim('index')
}

export { createModule }

0 comments on commit d7c8be8

Please sign in to comment.