Skip to content

Commit

Permalink
feat: [cloudflare workers] implement CLI command build-cloudflare-wor…
Browse files Browse the repository at this point in the history
…ker (#1)
  • Loading branch information
brillout committed Apr 10, 2021
1 parent dfa4e76 commit 7806f17
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 1 deletion.
90 changes: 90 additions & 0 deletions src/buildCloudflareWorker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { writeFile as writeFile_cb } from 'fs'
import { green, gray, cyan } from 'kolorist'
import * as rollup from 'rollup'
import esbuild from 'rollup-plugin-esbuild'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import nodePolyfills from 'rollup-plugin-polyfill-node'
import { assert } from './utils'
import { join, sep, relative } from 'path'

export { buildCloudflareWorker }

async function buildCloudflareWorker({ worker, root = process.cwd() }: { worker: string; root?: string }) {
console.log(
`${cyan(`vite-plugin-ssr ${require('../package.json').version}`)} ${green('building Cloudflare Worker...')}`
)

await buildImporter(root)

const inputOptions: rollup.InputOptions = {
input: worker,
plugins: [
esbuild({
sourceMap: false,
minify: false
}),
resolve(),
commonjs(),
json(),
nodePolyfills({ sourceMap: false }) as rollup.Plugin
],
onwarn(warning, warn) {
if (warning.code === 'CIRCULAR_DEPENDENCY') {
// Circular dependency warning doesn't seem to break build; https://github.com/snowpackjs/snowpack/pull/289#issuecomment-622167990
return
}
warn(warning)
}
}
const bundle = await rollup.rollup(inputOptions)
const dir = join('dist', 'server') + sep
const fileName = 'worker.js'
const file = join(relative(__dirname, root), dir, fileName)
const outputOptions: rollup.OutputOptions = {
format: 'iife',
exports: 'none',
file,
sourcemap: false
}
const { output } = await bundle.generate(outputOptions)
assert(output.length === 1)
assert(output[0].fileName === fileName)
console.log(`${gray(dir)}${cyan(fileName)}`)
console.log(`${green(`✓`)} Worker built.`)

// or write the bundle to disk
await bundle.write(outputOptions)

// closes the bundle
await bundle.close()
}

async function buildImporter(root: string): Promise<void> {
const importerCode = getImporterCode()
await writeFile(join(root, 'dist', 'server', 'importer.js'), importerCode)
}

function getImporterCode(): string {
return `// Import/require this file if you need to bundle your entire server code into a single file. For example for Cloudflare Workers.
// (The path of following dependencies are normally determined at run-time; this file makes them statically-analysable instead so that bundlers can determine the entire dependency tree at build-time.)
require("./infra.node.vite-entry.js");
const clientManifest = require("../client/manifest.json");
const serverManifest = require("../server/manifest.json");
const { __private_setViteManifest } = require("vite-plugin-ssr");
__private_setViteManifest({ clientManifest, serverManifest });
`
}

function writeFile(path: string, fileContent: string): Promise<void> {
return new Promise((resolve, reject) => {
writeFile_cb(path, fileContent, 'utf8', (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
5 changes: 5 additions & 0 deletions src/cli/bin.node.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { cac } from 'cac'
import { buildCloudflareWorker } from '../buildCloudflareWorker'
import { prerender } from '../prerender'

const cli = cac('vite-plugin-ssr')
Expand All @@ -17,6 +18,10 @@ cli
await prerender({ partial, clientRouter, base, root })
})

cli.command('build-cloudflare-worker <worker>').action(async (worker: string) => {
await buildCloudflareWorker({ worker })
})

// Listen to unknown commands
cli.on('command:*', () => {
console.error('Invalid command: %s', cli.args.join(' '))
Expand Down
1 change: 1 addition & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { prerender } from '../prerender'
export { buildCloudflareWorker } from '../buildCloudflareWorker'
9 changes: 8 additions & 1 deletion src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,17 @@
"@brillout/libassert": "^0.3.0",
"@brillout/path-to-regexp": "^0.1.2",
"@brillout/vite-fix-2390": "^0.3.0",
"@rollup/plugin-commonjs": "^18.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"cac": "^6.7.2",
"devalue": "^2.0.1",
"esbuild": "^0.11.6",
"fast-glob": "^3.2.5",
"kolorist": "^1.3.2"
"kolorist": "^1.3.2",
"rollup": "^2.44.0",
"rollup-plugin-esbuild": "^3.0.2",
"rollup-plugin-polyfill-node": "^0.6.2"
},
"devDependencies": {
"@types/node": "^14.14.37",
Expand Down

0 comments on commit 7806f17

Please sign in to comment.