Skip to content

Commit

Permalink
feat: universal import.meta (resolves #181)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 4, 2022
1 parent 9bf2d71 commit 929322b
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 28 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"dependencies": {
"@cloudflare/kv-asset-handler": "^0.2.0",
"@netlify/functions": "^1.0.0",
"@nuxt/devalue": "^2.0.0",
"@rollup/plugin-alias": "^3.1.9",
"@rollup/plugin-commonjs": "^22.0.0",
"@rollup/plugin-inject": "^4.0.4",
Expand Down
6 changes: 0 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const NitroDefaults: NitroConfig = {
analyze: false,
moduleSideEffects: ['unenv/runtime/polyfill/'],
replace: {},
node: true,
sourceMap: true,

// Advanced
Expand Down
50 changes: 30 additions & 20 deletions src/rollup/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { pathToFileURL } from 'url'
import { dirname, join, normalize, relative, resolve } from 'pathe'
import type { InputOptions, OutputOptions } from 'rollup'
import defu from 'defu'
import devalue from '@nuxt/devalue'
import { terser } from 'rollup-plugin-terser'
import commonjs from '@rollup/plugin-commonjs'
import { nodeResolve } from '@rollup/plugin-node-resolve'
Expand Down Expand Up @@ -133,20 +132,42 @@ export const getRollupConfig = (nitro: Nitro) => {
rollupConfig.plugins.push(wasmPlugin())
}

// Build-time environment variables
const buildEnvVars = {
NODE_ENV: nitro.options.dev ? 'development' : (nitro.options.preset === 'nitro-prerender' ? 'prerender' : 'production'),
server: true,
client: false,
dev: String(nitro.options.dev),
RUNTIME_CONFIG: nitro.options.runtimeConfig,
DEBUG: nitro.options.dev
}

// Universal import.meta
rollupConfig.plugins.push({
name: 'import-meta',
renderChunk (code, chunk) {
if (!chunk.isEntry) {
return
}
const url = nitro.options.node ? '_import_meta_url_' : '"file://_entry.js"'
const env = nitro.options.node ? 'process.env' : '{}'
return {
code: `globalThis._importMeta_={url:${url},env:${env}};` + code,
map: null
}
}
})

// https://github.com/rollup/plugins/tree/master/packages/replace
let NODE_ENV: string = nitro.options.dev ? 'development' : 'production'
if (nitro.options.preset === 'nitro-prerender') { NODE_ENV = 'prerender' }
rollupConfig.plugins.push(replace({
preventAssignment: true,
values: {
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'typeof window': '"undefined"',
_import_meta_url_: 'import.meta.url',
...Object.fromEntries(['.', ';', ')', '[', ']', '}', ' '].map(d => [`import.meta${d}`, `globalThis._importMeta_${d}`])),
...Object.fromEntries([';', '(', '{', '}', ' ', '\t', '\n'].map(d => [`${d}global.`, `${d}globalThis.`])),
'process.server': 'true',
'process.client': 'false',
'process.dev': String(nitro.options.dev),
'process.env.RUNTIME_CONFIG': devalue(nitro.options.runtimeConfig),
'process.env.DEBUG': JSON.stringify(nitro.options.dev),
...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => ([`process.env.${key}`, JSON.stringify(val)]))),
...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => ([`import.meta.env.${key}`, JSON.stringify(val)]))),
...nitro.options.replace
}
}))
Expand Down Expand Up @@ -175,17 +196,6 @@ export const getRollupConfig = (nitro: Nitro) => {
rollupConfig.plugins.push(serverAssets(nitro))

// Public assets
if (nitro.options.serveStatic) {
rollupConfig.plugins.push({
name: 'dirnames',
renderChunk (code, chunk) {
return {
code: (chunk.isEntry ? 'globalThis.entryURL = import.meta.url;' : '') + code,
map: null
}
}
})
}
rollupConfig.plugins.push(publicAssets(nitro))

// Storage
Expand Down
2 changes: 1 addition & 1 deletion src/rollup/plugins/public-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { resolve } from 'pathe'
import { dirname } from 'pathe'
import { fileURLToPath } from 'url'
import assets from '#internal/nitro/virtual/public-assets-data'
const mainDir = dirname(fileURLToPath(globalThis.entryURL))
const mainDir = dirname(fileURLToPath(import.meta.url))
export function readAsset (id) {
return fsp.readFile(resolve(mainDir, assets[id].path)).catch(() => {})
}`,
Expand Down
9 changes: 9 additions & 0 deletions test/fixture/api/import-meta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { fileURLToPath } from 'url'

export default () => {
return {
testFile: fileURLToPath(new URL('./test.txt', import.meta.url)),
// @ts-ignore
hasEnv: typeof import.meta.env === 'object'
}
}
7 changes: 7 additions & 0 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ export function testNitro (ctx: Context, getHandler: () => TestHandler | Promise
expect(heyData).to.have.string('Hey API')
})

it('universal import.meta', async () => {
const { status, data } = await callHandler({ url: '/api/import-meta' })
expect(status).toBe(200)
expect(data.testFile).toMatch(/\/test.txt$/)
expect(data.hasEnv).toBe(true)
})

if (ctx.nitro!.options.serveStatic) {
it('serve static asset /favicon.ico', async () => {
const { status, headers } = await callHandler({ url: '/favicon.ico' })
Expand Down

0 comments on commit 929322b

Please sign in to comment.