Skip to content

Commit

Permalink
feat: cjsBridge and emitCJS
Browse files Browse the repository at this point in the history
esm <3
  • Loading branch information
pi0 committed Oct 1, 2021
1 parent dc55de9 commit 74a64c1
Show file tree
Hide file tree
Showing 15 changed files with 130 additions and 22 deletions.
2 changes: 0 additions & 2 deletions bin/unbuild.cjs

This file was deleted.

2 changes: 2 additions & 0 deletions bin/unbuild.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env node
import '../dist/cli.mjs'
1 change: 1 addition & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { defineBuildConfig } from './src'

export default defineBuildConfig({
declaration: true,
emitCJS: false,
entries: [
'src/index',
'src/cli'
Expand Down
11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"description": "An unified javascript build system",
"repository": "unjs/unbuild",
"license": "MIT",
"main": "dist/index.cjs",
"exports": "./dist/index.mjs",
"types": "dist/index.d.ts",
"bin": {
"unbuild": "./bin/unbuild.cjs"
"unbuild": "./bin/unbuild.mjs"
},
"files": [
"bin",
Expand All @@ -28,23 +28,26 @@
"@rollup/plugin-commonjs": "^20.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.0.5",
"@rollup/plugin-replace": "^3.0.0",
"chalk": "^4.1.1",
"consola": "^2.15.3",
"defu": "^5.0.0",
"esbuild": "^0.13.3",
"jiti": "^1.12.5",
"magic-string": "^0.25.7",
"mkdirp": "^1.0.4",
"mkdist": "^0.3.3",
"mlly": "^0.2.4",
"mri": "^1.2.0",
"pathe": "^0.2.0",
"pretty-bytes": "^5.6.0",
"rimraf": "^3.0.2",
"rollup": "^2.57.0",
"rollup-plugin-dts": "^4.0.0",
"rollup-plugin-esbuild": "^4.5.0",
"scule": "^0.2.1",
"typescript": "^4.4.3",
"untyped": "^0.2.9",
"upath": "^2.0.1"
"untyped": "^0.2.9"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "latest",
Expand Down
6 changes: 4 additions & 2 deletions src/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Module from 'module'
import { resolve, basename } from 'upath'
import { resolve, basename } from 'pathe'
import chalk from 'chalk'
import consola from 'consola'
import defu from 'defu'
Expand Down Expand Up @@ -39,7 +39,9 @@ export async function build (rootDir: string, stub: boolean) {
clean: true,
stub,
buildEntries: [],
usedImports: new Set()
usedImports: new Set(),
emitCJS: true,
cjsBridge: false
} as BuildContext) as BuildContext

// Normalize entries
Expand Down
27 changes: 18 additions & 9 deletions src/builder/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,19 @@ import { nodeResolve } from '@rollup/plugin-node-resolve'
import alias from '@rollup/plugin-alias'
import esbuild from 'rollup-plugin-esbuild'
import dts from 'rollup-plugin-dts'
import { relative, resolve } from 'upath'
import { relative, resolve } from 'pathe'
import consola from 'consola'
import { getpkg } from '../utils'
import type { BuildContext } from '../types'
import { CJSBridgePlugin } from './utils/cjs-bridge'

export async function rollupBuild (ctx: BuildContext) {
if (ctx.stub) {
for (const entry of ctx.entries.filter(entry => entry.builder === 'rollup')) {
const output = resolve(ctx.rootDir, ctx.outDir, entry.name)
await writeFile(output + '.cjs', `module.exports = require('jiti')(null, { interopDefault: true })('${entry.input}')`)
if (ctx.emitCJS) {
await writeFile(output + '.cjs', `module.exports = require('jiti')(null, { interopDefault: true })('${entry.input}')`)
}
await writeFile(output + '.mjs', `import jiti from 'jiti';\nexport default jiti(null, { interopDefault: true })('${entry.input}');`)
await writeFile(output + '.d.ts', `export * from '${entry.input}'`)
}
Expand Down Expand Up @@ -71,7 +74,7 @@ export function getRollupOptions (ctx: BuildContext): RollupOptions {
),

output: [
{
ctx.emitCJS && {
dir: resolve(ctx.rootDir, ctx.outDir),
entryFileNames: '[name].cjs',
chunkFileNames: 'chunks/[name].cjs',
Expand All @@ -91,7 +94,7 @@ export function getRollupOptions (ctx: BuildContext): RollupOptions {
externalLiveBindings: false,
freeze: false
}
],
].filter(Boolean),

external (id) {
const pkg = getpkg(id)
Expand Down Expand Up @@ -126,7 +129,7 @@ export function getRollupOptions (ctx: BuildContext): RollupOptions {

{
name: 'json',
transform (json, id) {
transform (json: string, id: string) {
if (!id || id[0] === '\0' || !id.endsWith('.json')) { return null }
return {
code: 'module.exports = ' + json,
Expand All @@ -140,8 +143,14 @@ export function getRollupOptions (ctx: BuildContext): RollupOptions {
}),

commonjs({
extensions
})
]
}
extensions,
ignoreTryCatch: true
}),

// Preserve dynamic imports for CommonJS
{ renderDynamicImport () { return { left: 'import(', right: ')' } } },

ctx.cjsBridge && CJSBridgePlugin({})
].filter(Boolean)
} as RollupOptions
}
2 changes: 1 addition & 1 deletion src/builder/untyped.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { writeFile } from 'fs/promises'
import { resolve } from 'upath'
import { resolve } from 'pathe'
import { resolveSchema, generateTypes, generateMarkdown } from 'untyped'
import untypedPlugin from 'untyped/loader/babel'
import jiti from 'jiti'
Expand Down
45 changes: 45 additions & 0 deletions src/builder/utils/cjs-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { Plugin } from 'rollup'
import { findStaticImports } from 'mlly'
import MagicString from 'magic-string'

export function CJSBridgePlugin (_opts?: any): Plugin {
return {
name: 'cjs-bridge',
renderChunk (code, _chunk, opts) {
if (opts.format === 'es') {
return CJSToESM(code)
}
return null
}
} as Plugin
}

const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/

const CJSShim = `
// -- Unbuild CommonJS Shims --
import __cjs_url__ from 'url';
import __cjs_path__ from 'path';
import __cjs_mod__ from 'module';
const __filename = __cjs_url__.fileURLToPath(import.meta.url);
const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
`

// Shim __dirname, __filename and require
function CJSToESM (code: string) {
if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) {
return null
}

const lastESMImport = findStaticImports(code).pop()
const indexToAppend = lastESMImport ? lastESMImport.end : 0
const s = new MagicString(code)
s.appendRight(indexToAppend, CJSShim)

return {
code: s.toString(),
map: s.generateMap()
}
}
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolve } from 'upath'
import { resolve } from 'pathe'
import mri from 'mri'
import { build } from './build'

Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export interface BuildOptions {
devDependencies: string[]
externals: string[]
inlineDependencies: boolean
emitCJS: boolean
cjsBridge: boolean
}

export interface BuildContext extends BuildOptions {
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fsp from 'fs/promises'
import { promisify } from 'util'
import { dirname } from 'upath'
import { dirname } from 'pathe'
import mkdirp from 'mkdirp'
import _rimraf from 'rimraf'

Expand Down
1 change: 1 addition & 0 deletions test/fixture/build.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { BuildConfig } from 'unbuild'

export default <BuildConfig>{
cjsBridge: true,
entries: [
'src/index',
{ input: 'src/schema', builder: 'untyped' }
Expand Down
11 changes: 11 additions & 0 deletions test/fixture/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
import { arch } from 'os'

console.log('__filename', __filename)
console.log('__dirname', __dirname)
console.log('import.meta.url', import.meta.url)

console.log(arch())
console.log(require('os').arch())
console.log(require.resolve('rollup'))
import('os').then(os => console.log(os.arch()))

export const foo = 'bar'
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"module": "ESNext",
"moduleResolution": "Node",
"esModuleInterop": true,
"outDir": "dist",
Expand Down
36 changes: 35 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,14 @@
is-module "^1.0.0"
resolve "^1.19.0"

"@rollup/plugin-replace@^3.0.0":
version "3.0.0"
resolved "https://registry.yarnpkg.com/@rollup/plugin-replace/-/plugin-replace-3.0.0.tgz#3a4c9665d4e7a4ce2c360cf021232784892f3fac"
integrity sha512-3c7JCbMuYXM4PbPWT4+m/4Y6U60SgsnDT/cCyAyUKwFHg7pTSfsSQzIpETha3a3ig6OdOKzZz87D9ZXIK3qsDg==
dependencies:
"@rollup/pluginutils" "^3.1.0"
magic-string "^0.25.7"

"@rollup/pluginutils@^3.0.8", "@rollup/pluginutils@^3.1.0":
version "3.1.0"
resolved "https://registry.yarnpkg.com/@rollup/pluginutils/-/pluginutils-3.1.0.tgz#706b4524ee6dc8b103b3c995533e5ad680c02b9b"
Expand Down Expand Up @@ -651,6 +659,13 @@ builtin-modules@^3.1.0:
resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-3.2.0.tgz#45d5db99e7ee5e6bc4f362e008bf917ab5049887"
integrity sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA==

builtins@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/builtins/-/builtins-4.0.0.tgz#a8345420de82068fdc4d6559d0456403a8fb1905"
integrity sha512-qC0E2Dxgou1IHhvJSLwGDSTvokbRovU5zZFuDY6oY8Y2lF3nGt5Ad8YZK7GMtqzY84Wu7pXTPeHQeHcXSXsRhw==
dependencies:
semver "^7.0.0"

call-bind@^1.0.0, call-bind@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c"
Expand Down Expand Up @@ -1864,6 +1879,13 @@ import-fresh@^3.0.0, import-fresh@^3.2.1:
parent-module "^1.0.0"
resolve-from "^4.0.0"

import-meta-resolve@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-1.1.1.tgz#244fd542fd1fae73550d4f8b3cde3bba1d7b2b18"
integrity sha512-JiTuIvVyPaUg11eTrNDx5bgQ/yMKMZffc7YSjvQeSMXy58DO2SQ8BtAf3xteZvmzvjYh14wnqNjL8XVeDy2o9A==
dependencies:
builtins "^4.0.0"

import-modules@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/import-modules/-/import-modules-2.1.0.tgz#abe7df297cb6c1f19b57246eb8b8bd9664b6d8c2"
Expand Down Expand Up @@ -2313,6 +2335,13 @@ mkdist@^0.3.3:
upath "^2.0.1"
vue-template-compiler "^2.6.14"

mlly@^0.2.4:
version "0.2.4"
resolved "https://registry.yarnpkg.com/mlly/-/mlly-0.2.4.tgz#ab627afd1e999486bb9772f69c404482c4dfebcb"
integrity sha512-Wkv+SoSMoHUe9jkMKId08gj6JlSmCZ8TKGKhR3QcTFXaYml23oSk5qZWEDsvbzljeY3YZMnjzkSa365HaMzIJA==
dependencies:
import-meta-resolve "^1.1.1"

modify-values@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/modify-values/-/modify-values-1.0.1.tgz#b3939fa605546474e3e3e3c63d64bd43b4ee6022"
Expand Down Expand Up @@ -2557,6 +2586,11 @@ path-type@^4.0.0:
resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"
integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==

pathe@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/pathe/-/pathe-0.2.0.tgz#30fd7bbe0a0d91f0e60bae621f5d19e9e225c339"
integrity sha512-sTitTPYnn23esFR3RlqYBWn4c45WGeLcsKzQiUpXJAyfcWkolvlYpV8FLo7JishK946oQwMFUCHXQ9AjGPKExw==

picomatch@^2.2.2, picomatch@^2.2.3:
version "2.3.0"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972"
Expand Down Expand Up @@ -2811,7 +2845,7 @@ semver@^6.0.0, semver@^6.1.0, semver@^6.3.0:
resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d"
integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==

semver@^7.1.1, semver@^7.2.1, semver@^7.3.4, semver@^7.3.5:
semver@^7.0.0, semver@^7.1.1, semver@^7.2.1, semver@^7.3.4, semver@^7.3.5:
version "7.3.5"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7"
integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==
Expand Down

0 comments on commit 74a64c1

Please sign in to comment.