Created
August 4, 2022 01:33
-
-
Save hyrious/3040183d0b966f9696dca20ec9bdfb2d to your computer and use it in GitHub Desktop.
How to write pure JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import esbuild from "esbuild"; | |
import { rollup } from "rollup"; | |
import * as terser from "terser"; | |
async function runEsbuild(code) { | |
let result = await esbuild.transform(code, { treeShaking: true }); | |
return result.code; | |
} | |
async function runRollup(code) { | |
let modules = { "main.js": code }; | |
let bundle = await rollup({ | |
input: Object.keys(modules)[0], | |
plugins: [ | |
{ | |
resolveId(importee, importer) { | |
if (!importer) return importee; | |
if (importee[0] !== ".") return false; | |
}, | |
load(id) { | |
return modules[id]; | |
}, | |
}, | |
], | |
onwarn: () => {}, | |
}); | |
let generated = await bundle.generate({ format: "es" }); | |
return generated.output[0].code; | |
} | |
async function runTerser(code) { | |
const result = await terser.minify(code, { module: true }); | |
return result.code; | |
} | |
let count = 1; | |
async function runTests(code) { | |
function runX(f, name) { | |
console.log("--", name, "--"); | |
return f(code).then(console.log).catch(console.error); | |
} | |
console.log(`== Test ${count++} ==`); | |
console.log(code); | |
console.log(); | |
await runX(runTerser, "terser"); | |
await runX(runEsbuild, "esbuild"); | |
await runX(runRollup, "rollup"); | |
} | |
// NB. tests that comment out are almost the same | |
// await runTests(`let a = /* @__PURE__ */ f()`); | |
// await runTests(`let a = /* @__PURE__ */ f.g()`); | |
// await runTests(`let a = /* @__PURE__ */ f().g()`); | |
// await runTests(`let a = /* @__PURE__ */ f().g`); | |
// await runTests(`let a = /* @__PURE__ */ f.g`); | |
// await runTests(`let a = /* @__PURE__ */ f['g']()`); | |
// await runTests(`let a = /* @__PURE__ */ f()[g]()`); | |
// await runTests(`let a = /* @__PURE__ */ f[g]`); | |
await runTests(`let a = Object.prototype.hasOwnProperty`); | |
await runTests(`let a = Object.hasOwn`); | |
// await runTests(`let a = Whatever.whatever`); | |
await runTests(`let a = /* @__PURE__ */ import('b')`); | |
await runTests(`let a = new Map()`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Conclusions:
let a = 1
let a = 1 << 1
enum
in TypeScript format.let a = {}; a.b = 1
a
, which is not supported in esbuild.The return value of
f.g().h()
is pure, but it is then be used in$ret.i
, which makes the whole expression not pure. If you need an explanation: there may exist aget i() {}
which has side effects.The whole iife function call is safe to remove if
a
is not used somewhere else.