Skip to content

Commit

Permalink
feat: use native esm for all packages (#539)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Oct 2, 2021
1 parent fe876a9 commit cf4d593
Show file tree
Hide file tree
Showing 19 changed files with 76 additions and 64 deletions.
1 change: 1 addition & 0 deletions src/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
declaration: true,
emitCJS: false,
entries: [
'src/index',
{ input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm' },
Expand Down
10 changes: 5 additions & 5 deletions src/build.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { resolve, join } from 'pathe'
import consola from 'consola'
import { rollup, watch as rollupWatch } from 'rollup'
import { readFile, emptyDir, copy } from 'fs-extra'
import fse from 'fs-extra'
import { printFSTree } from './utils/tree'
import { getRollupConfig } from './rollup/config'
import { hl, prettyPath, serializeTemplate, writeFile, isDirectory } from './utils'
Expand All @@ -24,20 +24,20 @@ export async function prepare (nitroContext: NitroContext) {

async function cleanupDir (dir: string) {
consola.info('Cleaning up', prettyPath(dir))
await emptyDir(dir)
await fse.emptyDir(dir)
}

export async function generate (nitroContext: NitroContext) {
consola.start('Generating public...')

const clientDist = resolve(nitroContext._nuxt.buildDir, 'dist/client')
if (await isDirectory(clientDist)) {
await copy(clientDist, join(nitroContext.output.publicDir, nitroContext._nuxt.publicPath))
await fse.copy(clientDist, join(nitroContext.output.publicDir, nitroContext._nuxt.publicPath))
}

const publicDir = nitroContext._nuxt.publicDir
if (await isDirectory(publicDir)) {
await copy(publicDir, nitroContext.output.publicDir)
await fse.copy(publicDir, nitroContext.output.publicDir)
}

consola.success('Generated public ' + prettyPath(nitroContext.output.publicDir))
Expand All @@ -48,7 +48,7 @@ export async function build (nitroContext: NitroContext) {
const htmlSrc = resolve(nitroContext._nuxt.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`)
const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' }
htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.mjs').replace('app.', 'document.')
htmlTemplate.contents = nitroContext.vfs[htmlTemplate.src] || await readFile(htmlTemplate.src, 'utf-8')
htmlTemplate.contents = nitroContext.vfs[htmlTemplate.src] || await fse.readFile(htmlTemplate.src, 'utf-8')
await nitroContext._internal.hooks.callHook('nitro:document', htmlTemplate)
htmlTemplate.compiled = 'export default ' + serializeTemplate(htmlTemplate.contents)
await writeFile(htmlTemplate.dst, htmlTemplate.compiled)
Expand Down
3 changes: 0 additions & 3 deletions src/compat.js

This file was deleted.

6 changes: 3 additions & 3 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable no-use-before-define */

import { resolve, dirname } from 'pathe'
import { resolve } from 'pathe'
import defu from 'defu'
import { createHooks, Hookable, NestedHooks } from 'hookable'
import type { Preset } from 'unenv'
Expand All @@ -13,6 +12,7 @@ import type { AssetOptions } from './rollup/plugins/assets'
import type { ServerMiddleware } from './server/middleware'
import type { RollupConfig } from './rollup/config'
import type { Options as EsbuildOptions } from './rollup/plugins/esbuild'
import { runtimeDir } from './dirs'

export interface NitroHooks {
'nitro:document': (htmlTemplate: { src: string, contents: string, dst: string, compiled: string }) => void
Expand Down Expand Up @@ -136,7 +136,7 @@ export function getNitroContext (nuxtOptions: NuxtOptions, input: NitroInput): N
}
},
_internal: {
runtimeDir: resolve(dirname(require.resolve('@nuxt/nitro')), 'runtime'),
runtimeDir,
hooks: createHooks<NitroHooks>()
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/dirs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { fileURLToPath } from 'url'
import { dirname, resolve } from 'pathe'

export const distDir = dirname(fileURLToPath(import.meta.url))
export const pkgDir = resolve(distDir, '..')
export const runtimeDir = resolve(distDir, 'runtime')
8 changes: 4 additions & 4 deletions src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
"name": "@nuxt/nitro",
"version": "0.10.0",
"license": "MIT",
"main": "./dist/index.cjs",
"type": "module",
"exports": "./dist/index.mjs",
"types": "./types/index.d.ts",
"files": [
"dist",
"types",
"compat.js"
"types"
],
"scripts": {
"prepack": "unbuild"
Expand Down Expand Up @@ -50,6 +50,7 @@
"jiti": "^1.12.6",
"listhen": "^0.2.4",
"mime": "^2.5.2",
"mlly": "^0.2.2",
"node-fetch": "^3.0.0",
"ohmyfetch": "^0.3.1",
"ora": "^6.0.1",
Expand All @@ -65,7 +66,6 @@
"ufo": "^0.7.9",
"unenv": "^0.3.10",
"unstorage": "^0.2.8",
"upath": "^2.0.1",
"vue": "3.2.19",
"vue-bundle-renderer": "^0.3.1",
"vue-server-renderer": "^2.6.14"
Expand Down
2 changes: 1 addition & 1 deletion src/presets/azure_functions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createWriteStream } from 'fs'
import archiver from 'archiver'
import consola from 'consola'
import { createWriteStream } from 'fs-extra'
import { join, resolve } from 'pathe'
import { prettyPath, writeFile } from '../utils'
import { NitroPreset, NitroContext } from '../context'
Expand Down
10 changes: 5 additions & 5 deletions src/presets/browser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, writeFile } from 'fs-extra'
import { existsSync, promises as fsp } from 'fs'
import { resolve } from 'pathe'
import consola from 'consola'
import { extendPreset, prettyPath } from '../utils'
Expand Down Expand Up @@ -62,17 +62,17 @@ if ('serviceWorker' in navigator) {
tmpl.compiled = tmpl.compiled.replace('</body>', script + '</body>')
},
async 'nitro:compiled' ({ output }: NitroContext) {
await writeFile(resolve(output.publicDir, 'sw.js'), `self.importScripts('${input._nuxt.routerBase}_server/index.mjs');`)
await fsp.writeFile(resolve(output.publicDir, 'sw.js'), `self.importScripts('${input._nuxt.routerBase}_server/index.mjs');`, 'utf8')

// Temp fix
if (!existsSync(resolve(output.publicDir, 'index.html'))) {
await writeFile(resolve(output.publicDir, 'index.html'), html)
await fsp.writeFile(resolve(output.publicDir, 'index.html'), html, 'utf8')
}
if (!existsSync(resolve(output.publicDir, '200.html'))) {
await writeFile(resolve(output.publicDir, '200.html'), html)
await fsp.writeFile(resolve(output.publicDir, '200.html'), html, 'utf8')
}
if (!existsSync(resolve(output.publicDir, '404.html'))) {
await writeFile(resolve(output.publicDir, '404.html'), html)
await fsp.writeFile(resolve(output.publicDir, '404.html'), html, 'utf8')
}
consola.info('Ready to deploy to static hosting:', prettyPath(output.publicDir as string))
}
Expand Down
15 changes: 9 additions & 6 deletions src/presets/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createRequire } from 'module'
import { join, relative, resolve } from 'pathe'
import { existsSync, readJSONSync } from 'fs-extra'
import fse from 'fs-extra'
import consola from 'consola'
import globby from 'globby'

Expand All @@ -16,7 +17,7 @@ export const firebase: NitroPreset = {
}

async function writeRoutes ({ output: { publicDir, serverDir }, _nuxt: { rootDir } }: NitroContext) {
if (!existsSync(join(rootDir, 'firebase.json'))) {
if (!fse.existsSync(join(rootDir, 'firebase.json'))) {
const firebase = {
functions: {
source: relative(rootDir, serverDir)
Expand All @@ -38,20 +39,22 @@ async function writeRoutes ({ output: { publicDir, serverDir }, _nuxt: { rootDir
await writeFile(resolve(rootDir, 'firebase.json'), JSON.stringify(firebase))
}

const _require = createRequire(import.meta.url)

const jsons = await globby(`${serverDir}/node_modules/**/package.json`)
const prefixLength = `${serverDir}/node_modules/`.length
const suffixLength = '/package.json'.length
const dependencies = jsons.reduce((obj, packageJson) => {
const dirname = packageJson.slice(prefixLength, -suffixLength)
if (!dirname.includes('node_modules')) {
obj[dirname] = require(packageJson).version
obj[dirname] = _require(packageJson).version
}
return obj
}, {} as Record<string, string>)

let nodeVersion = '12'
try {
const currentNodeVersion = readJSONSync(join(rootDir, 'package.json')).engines.node
const currentNodeVersion = fse.readJSONSync(join(rootDir, 'package.json')).engines.node
if (['12', '10'].includes(currentNodeVersion)) {
nodeVersion = currentNodeVersion
}
Expand All @@ -66,8 +69,8 @@ async function writeRoutes ({ output: { publicDir, serverDir }, _nuxt: { rootDir
dependencies,
devDependencies: {
'firebase-functions-test': 'latest',
'firebase-admin': require('firebase-admin/package.json').version,
'firebase-functions': require('firebase-functions/package.json')
'firebase-admin': _require('firebase-admin/package.json').version,
'firebase-functions': _require('firebase-functions/package.json')
.version
},
engines: { node: nodeVersion }
Expand Down
6 changes: 3 additions & 3 deletions src/presets/netlify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync, promises as fsp } from 'fs'
import { join } from 'pathe'
import { existsSync, readFile, writeFile } from 'fs-extra'
import consola from 'consola'
import { extendPreset } from '../utils'
import { NitroContext, NitroPreset } from '../context'
Expand All @@ -15,15 +15,15 @@ export const netlify: NitroPreset = extendPreset(lambda, {
const redirectsPath = join(ctx.output.publicDir, '_redirects')
let contents = '/* /.netlify/functions/server 200'
if (existsSync(redirectsPath)) {
const currentRedirects = await readFile(redirectsPath, 'utf-8')
const currentRedirects = await fsp.readFile(redirectsPath, 'utf-8')
if (currentRedirects.match(/^\/\* /m)) {
consola.info('Not adding Nitro fallback to `_redirects` (as an existing fallback was found).')
return
}
consola.info('Adding Nitro fallback to `_redirects` to handle all unmatched routes.')
contents = currentRedirects + '\n' + contents
}
await writeFile(redirectsPath, contents)
await fsp.writeFile(redirectsPath, contents)
},
'nitro:rollup:before' (ctx: NitroContext) {
ctx.rollupConfig.output.entryFileNames = 'server.ts'
Expand Down
15 changes: 9 additions & 6 deletions src/rollup/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { pathToFileURL } from 'url'
import { dirname, join, normalize, relative, resolve } from 'pathe'
import { createRequire } from 'module'
import { dirname, join, relative, resolve } from 'pathe'
import type { InputOptions, OutputOptions } from 'rollup'
import defu from 'defu'
import { terser } from 'rollup-plugin-terser'
Expand All @@ -15,7 +16,8 @@ import * as unenv from 'unenv'

import type { Preset } from 'unenv'
import { NitroContext } from '../context'
import { resolvePath, MODULE_DIR } from '../utils'
import { resolvePath } from '../utils'
import { pkgDir } from '../dirs'

import { dynamicRequire } from './plugins/dynamic-require'
import { externals } from './plugins/externals'
Expand Down Expand Up @@ -63,10 +65,11 @@ export const getRollupConfig = (nitroContext: NitroContext) => {
}

// TODO: #590
const _require = createRequire(import.meta.url)
if (nitroContext._nuxt.majorVersion === 3) {
env.alias['vue/server-renderer'] = 'vue/server-renderer'
env.alias['vue/compiler-sfc'] = 'vue/compiler-sfc'
env.alias.vue = require.resolve(`vue/dist/vue.cjs${nitroContext._nuxt.dev ? '' : '.prod'}.js`)
env.alias.vue = _require.resolve(`vue/dist/vue.cjs${nitroContext._nuxt.dev ? '' : '.prod'}.js`)
}

const buildServerDir = join(nitroContext._nuxt.buildDir, 'dist/server')
Expand Down Expand Up @@ -216,8 +219,8 @@ export const getRollupConfig = (nitroContext: NitroContext) => {
rollupConfig.plugins.push(alias({
entries: {
'#nitro': nitroContext._internal.runtimeDir,
'#nitro-renderer': normalize(require.resolve(resolve(nitroContext._internal.runtimeDir, 'app', renderer))),
'#config': normalize(require.resolve(resolve(nitroContext._internal.runtimeDir, 'app/config'))),
'#nitro-renderer': resolve(nitroContext._internal.runtimeDir, 'app', renderer),
'#config': resolve(nitroContext._internal.runtimeDir, 'app/config'),
'#nitro-vue-renderer': vue2ServerRenderer,
// Only file and data URLs are supported by the default ESM loader on Windows (#427)
'#build': nitroContext._nuxt.dev && process.platform === 'win32'
Expand All @@ -234,7 +237,7 @@ export const getRollupConfig = (nitroContext: NitroContext) => {
const moduleDirectories = [
resolve(nitroContext._nuxt.rootDir, 'node_modules'),
...nitroContext._nuxt.modulesDir,
resolve(MODULE_DIR, '../node_modules'),
resolve(pkgDir, '../node_modules'),
'node_modules'
]

Expand Down
16 changes: 9 additions & 7 deletions src/rollup/plugins/dynamic-require.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { pathToFileURL } from 'url'
import { resolve } from 'pathe'
import globby from 'globby'
import type { Plugin } from 'rollup'
import { serializeImportName } from '../../utils'

const PLUGIN_NAME = 'dynamic-require'
const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.js`
const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.mjs`
const DYNAMIC_REQUIRE_RE = /import\("\.\/" ?\+(.*)\).then/g

interface Options {
Expand Down Expand Up @@ -57,24 +58,25 @@ export function dynamicRequire ({ dir, ignore, inline }: Options): Plugin {
let files = []
try {
const wpManifest = resolve(dir, './server.manifest.json')
files = await import(wpManifest).then(r => Object.keys(r.files).filter(file => !ignore.includes(file)))
files = await import(pathToFileURL(wpManifest).href).then(r => Object.keys(r.files).filter(file => !ignore.includes(file)))
} catch {
files = await globby('**/*.{cjs,mjs,js}', { cwd: dir, absolute: false, ignore })
}
const chunks = files.map(id => ({

const chunks = (await Promise.all(files.map(async id => ({
id,
src: resolve(dir, id).replace(/\\/g, '/'),
name: serializeImportName(id),
meta: getWebpackChunkMeta(resolve(dir, id))
})).filter(chunk => chunk.meta)
meta: await getWebpackChunkMeta(resolve(dir, id))
})))).filter(chunk => chunk.meta)

return inline ? TMPL_INLINE({ chunks }) : TMPL_LAZY({ chunks })
}
}
}

function getWebpackChunkMeta (src: string) {
const chunk = require(src) || {}
async function getWebpackChunkMeta (src: string) {
const chunk = await import(pathToFileURL(src).href).then(r => r.default || r || {})
const { id, ids, modules } = chunk
if (!id && !ids) {
return null // Not a webpack chunk
Expand Down
6 changes: 3 additions & 3 deletions src/rollup/plugins/externals.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { resolve, dirname } from 'pathe'
import { copyFile, mkdirp } from 'fs-extra'
import fse from 'fs-extra'
import { nodeFileTrace, NodeFileTraceOptions } from '@vercel/nft'
import type { Plugin } from 'rollup'

Expand Down Expand Up @@ -84,8 +84,8 @@ export function externals (opts: NodeExternalsOptions): Plugin {
const writeFile = async (file) => {
const src = resolve(opts.traceOptions.base, file)
const dst = resolve(opts.outDir, 'node_modules', file.split('node_modules/').pop())
await mkdirp(dirname(dst))
await copyFile(src, dst)
await fse.mkdirp(dirname(dst))
await fse.copyFile(src, dst)
}
if (process.platform === 'win32') {
// Workaround for EBUSY on windows (#424)
Expand Down
2 changes: 1 addition & 1 deletion src/rollup/plugins/static.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync, statSync } from 'fs'
import createEtag from 'etag'
import { readFileSync, statSync } from 'fs-extra'
import mime from 'mime'
import { relative, resolve } from 'pathe'
import virtual from '@rollup/plugin-virtual'
Expand Down
6 changes: 3 additions & 3 deletions src/rollup/plugins/virtual.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as path from 'pathe'
import { resolve, dirname } from 'pathe'
import type { Plugin } from 'rollup'

// Based on https://github.com/rollup/plugins/blob/master/packages/virtual/src/index.ts
Expand All @@ -16,7 +16,7 @@ export default function virtual (modules: RollupVirtualOptions): Plugin {

for (const [id, mod] of Object.entries(modules)) {
_modules.set(id, mod)
_modules.set(path.resolve(id), mod)
_modules.set(resolve(id), mod)
}

return {
Expand All @@ -29,7 +29,7 @@ export default function virtual (modules: RollupVirtualOptions): Plugin {
const importerNoPrefix = importer.startsWith(PREFIX)
? importer.slice(PREFIX.length)
: importer
const resolved = path.resolve(path.dirname(importerNoPrefix), id)
const resolved = resolve(dirname(importerNoPrefix), id)
if (_modules.has(resolved)) { return PREFIX + resolved }
}

Expand Down
4 changes: 2 additions & 2 deletions src/runtime/entries/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import '#polyfill'

// @ts-ignore
import functions from 'firebase-functions'
import { handle } from '../server'

const functions = require('firebase-functions')

export const server = functions.https.onRequest(handle)
Loading

0 comments on commit cf4d593

Please sign in to comment.