Skip to content

Commit 6c0d05a

Browse files
authored
Polyfill import.meta.url for CJS builds (#217)
1 parent 312828b commit 6c0d05a

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

import.meta.url-polyfill.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const import_meta_url = typeof document === 'undefined'
2+
? new (require('url'.replace('', '')).URL)('file:' + __filename).href
3+
: (document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href)

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
"build": "npm run build-plugin && npm run build-inertia-helpers",
3434
"build-plugin": "rm -rf dist && npm run build-plugin-types && npm run build-plugin-esm && npm run build-plugin-cjs && cp src/dev-server-index.html dist/",
3535
"build-plugin-types": "tsc --emitDeclarationOnly",
36-
"build-plugin-cjs": "esbuild src/index.ts --platform=node --format=cjs --outfile=dist/index.cjs",
36+
"build-plugin-cjs": "esbuild src/index.ts --platform=node --format=cjs --outfile=dist/index.cjs --define:import.meta.url=import_meta_url --inject:./import.meta.url-polyfill.js",
3737
"build-plugin-esm": "esbuild src/index.ts --platform=node --format=esm --outfile=dist/index.mjs",
3838
"build-inertia-helpers": "rm -rf inertia-helpers && tsc --project tsconfig.inertia-helpers.json",
3939
"lint": "eslint --ext .ts ./src ./tests",

src/index.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from 'fs'
22
import { AddressInfo } from 'net'
33
import os from 'os'
4+
import { fileURLToPath } from 'url'
45
import path from 'path'
56
import colors from 'picocolors'
67
import { Plugin, loadEnv, UserConfig, ConfigEnv, ResolvedConfig, SSROptions, PluginOption } from 'vite'
@@ -224,7 +225,7 @@ function resolveLaravelPlugin(pluginConfig: Required<PluginConfig>): LaravelPlug
224225
res.statusCode = 404
225226

226227
res.end(
227-
fs.readFileSync(path.join(__dirname, 'dev-server-index.html')).toString().replace(/{{ APP_URL }}/g, appUrl)
228+
fs.readFileSync(path.join(dirname(), 'dev-server-index.html')).toString().replace(/{{ APP_URL }}/g, appUrl)
228229
)
229230
}
230231

@@ -277,7 +278,7 @@ function laravelVersion(): string {
277278
*/
278279
function pluginVersion(): string {
279280
try {
280-
return JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json')).toString())?.version
281+
return JSON.parse(fs.readFileSync(path.join(dirname(), '../package.json')).toString())?.version
281282
} catch {
282283
return ''
283284
}
@@ -537,3 +538,10 @@ function resolveValetHost(): string {
537538

538539
return path.basename(process.cwd()) + '.' + config.tld
539540
}
541+
542+
/**
543+
* The directory of the current file.
544+
*/
545+
function dirname(): string {
546+
return fileURLToPath(new URL('.', import.meta.url))
547+
}

0 commit comments

Comments
 (0)