Skip to content

Commit

Permalink
Cjs2esm (#507)
Browse files Browse the repository at this point in the history
use own esm converter
  • Loading branch information
andypf authored Jan 17, 2024
1 parent 20be10a commit 49c594c
Show file tree
Hide file tree
Showing 96 changed files with 8,388 additions and 7,085 deletions.
12 changes: 5 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
node_modules

.npm/*
scripts/test_data
scripts/externals
scripts/im.json
scripts/manifest.json
scripts/importmap.json
ci/scripts/test_data
ci/scripts/externals
ci/scripts/im.json
ci/scripts/manifest.json
ci/scripts/importmap.json

# local assets-server build
assets_server_build
Expand All @@ -21,8 +21,6 @@ build
/build
/ci/pipeline.yaml

scripts/test_data

# misc
.DS_Store
.env.local
Expand Down
154 changes: 154 additions & 0 deletions TEST/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />

<title>Template Dev</title>
<script
async
src="https://ga.jspm.io/npm:[email protected]/dist/es-module-shims.js"
></script>
<style>
h1::before {
transform: scaleX(0);
transform-origin: bottom right;
}

h1:hover::before {
transform: scaleX(1);
transform-origin: bottom left;
}

h1::before {
content: " ";
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
inset: 0 0 0 0;
background: hsl(200 100% 80%);
z-index: -1;
transition: transform 0.3s ease;
}

h1 {
position: relative;
font-size: 5rem;
}
</style>

<!-- https://generator.jspm.io/#U2NhYGBkDM0rySzJSU1hKEpNTC5xMLTQM9Az0C1K1jMAAKFS5w0gAA -->
<!-- <script type="importmap">
{
"imports": {
"react": "https:/esm.sh/[email protected]",
"@tanstack/react-query": "https://esm.sh/@tanstack/[email protected]",
"custom-event-polyfill": "https://esm.sh/custom-event-polyfill@^1.0.7",
"juno-ui-components": "https://assets.juno.global.cloud.sap/juno-ui-components@latest/build/index.js",
"luxon": "https://esm.sh/luxon@^2.3.0",
"prop-types": "https://esm.sh/prop-types@^15.8.1",
"react-dom": "https://esm.sh/react-dom@^18.2.0",
"zustand": "https://esm.sh/[email protected]",
"react-dom": "https://esm.sh/react-dom@^18",
"react-dom/": "https://esm.sh/react-dom@^18/"
}
}
</script> -->

<!-- <script type="importmap">
{
"imports": {
"react": "/build/esm/[email protected]",
"@tanstack/react-query": "https://esm.sh/@tanstack/[email protected]",
"custom-event-polyfill": "https://esm.sh/custom-event-polyfill@^1.0.7",
"juno-ui-components": "https://assets.juno.global.cloud.sap/juno-ui-components@latest/build/index.js",
"luxon": "https://esm.sh/luxon@^2.3.0",
"prop-types": "https://esm.sh/prop-types@^15.8.1",
"react-dom": "https://esm.sh/react-dom@^18.2.0",
"zustand": "https://esm.sh/[email protected]",
"react-dom": "/build/esm/[email protected]",
"react-dom/": "https:/esm.sh/[email protected]/"
}
}
</script> -->
<script type="importmap">
{
"imports": {
"react": "/build/[email protected]/index.js",
"react/": "/build/[email protected]/",
"react-dom": "/build/[email protected]/index.js",
"react-dom/client": "/build/[email protected]/client.js",
"react-dom/": "/build/[email protected]/",
"scheduler": "/build/[email protected]/index.js",
"scheduler/": "/build/[email protected]/",
"zustand": "/build/[email protected]/index.js",
"zustand/vanilla": "/build/[email protected]/vanilla.js"
}
}
</script>
</head>
<body>
<script type="module">
import React, { useState } from "react"
import { createRoot } from "react-dom/client"
import { create } from "zustand"

const useBearStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))

const domNode = document.getElementById("root")
const root = createRoot(domNode)

// console.log(root, React.version)
// const App = () => {
// const [greetings, updateGGreetings] = useState()
// return React.createElement("h1", null, `Hello World`)
// }
const App = () => {
const bears = useBearStore((state) => state.bears)
const increasePopulation = useBearStore(
(state) => state.increasePopulation
)

const greetingsValues = [
"World",
"Universe",
"Galaxy",
"Solar System",
"Folks",
"People",
"Humans",
"Earth",
"Mars",
"Venus",
]
const [greetings, updateGGreetings] = useState(greetingsValues[0])

// const [greetings, updateGreetings] = ["World"]
React.useEffect(() => {
let i = 0
const interval = setInterval(() => {
i++
updateGGreetings(greetingsValues[i % greetingsValues.length])
}, Math.random() * 10000)
return () => clearInterval(interval)
}, [])
return React.createElement("div", null, [
React.createElement("h1", { key: 0 }, `Hello ${greetings} ${bears}`),
React.createElement(
"button",
{ onClick: increasePopulation, key: 1 },
"one up"
),
])
}
root.render(React.createElement(App))
</script>
<div id="root" data-juno-app="zt"></div>
</body>
</html>
98 changes: 98 additions & 0 deletions TEST/scripts/v1/cjs_to_esm_esbuild_pluginV1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const fs = require("fs")
const path = require("path")
// const { parse } = require("cjs-module-lexer")
const { parse } = require("esm-cjs-lexer")
const { resolve } = require("path")
const { parseCjsExports } = require("./helper")

const cjs_to_esm_plugin = {
name: "cjs-to-esm",
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
// console.log("::::::::::::", args)
if (args.importer === "") return { path: args.path, namespace: "cjs2esm" }
})
build.onLoad({ filter: /.*/, namespace: "cjs2esm" }, async (args) => {
// console.log("::::::::::::", args)
//const code = fs.readFileSync(args.path, "utf8")

// const result = parse(args.path, code)
// const keys = Object.keys(require(args.path)).join(", ")
const filePath = JSON.stringify(args.path)
const resolveDir = __dirname

// console.log(":::PATH", filePath)
// console.log(":::EXPORTS, REEXPORTS", result)

// const namedExports = []
// namedExports.push(`export { ${result.exports.join(", ")} }`)

// result.reexports.forEach((reexport) => {
// const importPath = path.resolve(args.path, "../", reexport)
// const imports = require(importPath)
// const importKeys = Object.keys(imports)

// if (importKeys.length === 0)
// namedExports.push(
// `export {default} from ${JSON.stringify(importPath)}`
// )
// else
// namedExports.push(
// `export { default, ${importKeys.join(", ")} } from ${JSON.stringify(
// importPath
// )}`
// )
// })

// console.log("===", namedExports.join("\n"))
// console.log(":::----", keys)

// let namedExports2 = await parseCjsExports({
// cwd: args.path,
// importPath: path.resolve(args.path, "../"),
// })

// namedExports2 = `
// export { default, ${namedExports2.exports.join(", ")} } from ${filePath}`

// console.log("------------------------")
// console.log(":::", namedExports2)
// console.log("---", `export { default, ${keys} } from ${filePath}`)
// console.log(
// "cjs-to-esm",
// args,
// `export export { default, ${keys} } from ${path}`
// )

// return {
// contents: `export { default, ${keys} } from ${filePath}`,
// resolveDir,
// }

return {
contents: namedExports2,
//resolveDir: path.dirname(args.path), //resolveDir,
resolveDir,
}

// console.log(`
// import * as m from ${filePath};
// import { ${keys} } from ${filePath};
// export { ${keys} };
// export default m;
// `)

// return {
// contents: `
// import * as m from ${filePath};
// import { ${keys} } from ${filePath};
// export { ${keys} };
// export default m;
// `,
// resolveDir,
// }
})
},
}

module.exports = cjs_to_esm_plugin
77 changes: 77 additions & 0 deletions TEST/scripts/v1/toEsmV1.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import fs from "fs"
import path from "path"
import child_process from "child_process"
import esbuild from "esbuild"
import cjsToEsm from "./cjs_to_esm_esbuild_plugin.js"

// let tmpDir = path.join(__dirname, "TEST")
let tmpDir = "/app/TEST/build"

fs.rmSync(tmpDir, { recursive: true, force: true })
fs.mkdirSync(path.resolve(tmpDir, "esm"), { recursive: true })

fs.writeFileSync(
path.join(tmpDir, "package.json"),
// JSON.stringify({ dependencies: { react: "^18.2.0" } }, null, 2)
JSON.stringify({ dependencies: { react: "*", "react-dom": "*" } }, null, 2)
)

child_process.execSync("npm install", { stdio: [0, 1, 2], cwd: tmpDir })

// for all packages in tmpDir/node_modules
fs.readdirSync(path.join(tmpDir, "node_modules")).forEach(async (pkg) => {
let pkgPath = path.join(tmpDir, "node_modules", pkg)
if (fs.statSync(pkgPath).isDirectory()) {
let pkgJsonPath = path.join(pkgPath, "package.json")
if (fs.existsSync(pkgJsonPath)) {
let pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath))
// ONLY react for now

if (pkgJson.name !== "react" && pkgJson.name !== "react-dom") return
console.log("===========proceed", pkgJson.name)

if (pkgJson.main) {
let pkgMainPath = path.join(pkgPath, pkgJson.main)
let pkgMainEsmPath = path.join(
tmpDir,
"esm",
pkgJson.name + "@" + pkgJson.version + ".js"
)
if (fs.existsSync(pkgMainPath)) {
const c = fs.readFileSync(pkgMainPath)
// console.log(c.toString())
// const { code, map } = await transform(c.toString())
// fs.writeFileSync(pkgMainPath, code)

// console.log("=============", pkgJson.name, code)
const outdir = path.resolve(
tmpDir,
"esm",
`${pkgJson.name}@${pkgJson.version}`
)

// const result = acorn.parse(c.toString(), {ecmaVersion: 2020})

await esbuild.build({
entryPoints: [pkgMainPath],
format: "esm",
bundle: true,
minify: true,
outdir,
plugins: [cjsToEsm],
})
}
}
}
}
})

child_process.execSync("ls -la", { stdio: [0, 1, 2], cwd: tmpDir })
// npm.load(myConfigObject, function (er) {
// if (er) return handlError(er)
// npm.commands.install(['some', 'args'], function (er, data) {
// if (er) return commandFailed(er)
// // command succeeded, and data might have some info
// })
// npm.registry.log.on('log', function (message) { ... })
// })
Loading

0 comments on commit 49c594c

Please sign in to comment.