fix: now cjs shims should only be injected when it's actually used

This commit is contained in:
EGOIST 2021-12-08 00:38:36 +08:00
parent 993fe56c4a
commit a6e06e8963
5 changed files with 18 additions and 9 deletions

View File

@ -1,7 +1,12 @@
// Shim globals in cjs bundle
// There's a weird bug that esbuild will always inject importMetaUrl
// if we export it as `const importMetaUrl = ... __filename ...`
// But using a function will not cause this issue
export const importMetaUrlShim =
const getImportMetaUrl = () =>
typeof document === 'undefined'
? new URL('file:' + __filename).href
: (document.currentScript && document.currentScript.src) ||
new URL('main.js', document.baseURI).href
export const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()

View File

@ -2,7 +2,8 @@
import { fileURLToPath } from 'url'
import path from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const getFilename = () => fileURLToPath(import.meta.url)
const getDirname = () => path.dirname(getFilename())
export { __dirname, __filename }
export const __dirname = /* @__PURE__ */ getDirname()
export const __filename = /* @__PURE__ */ getFilename()

View File

@ -158,7 +158,7 @@ export async function runEsbuild(
define: {
...(format === 'cjs' && injectShims
? {
'import.meta.url': 'importMetaUrlShim',
'import.meta.url': 'importMetaUrl',
}
: {}),
...options.define,

View File

@ -393,10 +393,11 @@ Generated by [AVA](https://avajs.dev).
});␊
// ../../../assets/cjs_shims.js␊
var importMetaUrlShim = typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;␊
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;␊
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();␊
// input.ts␊
var input_default = importMetaUrlShim;␊
var input_default = importMetaUrl;␊
// Annotate the CommonJS export names for ESM import in node:␊
0 && (module.exports = {});␊
`
@ -408,8 +409,10 @@ Generated by [AVA](https://avajs.dev).
`// ../../../assets/esm_shims.js␊
import { fileURLToPath } from "url";␊
import path from "path";␊
var __filename = fileURLToPath(import.meta.url);␊
var __dirname = path.dirname(__filename);␊
var getFilename = () => fileURLToPath(import.meta.url);␊
var getDirname = () => path.dirname(getFilename());␊
var __dirname = /* @__PURE__ */ getDirname();␊
var __filename = /* @__PURE__ */ getFilename();␊
// input.ts␊
var a = __dirname;␊

Binary file not shown.