-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(): support for __dirname and __filename
- Loading branch information
1 parent
f796e4d
commit 9fb7678
Showing
3 changed files
with
33 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,48 @@ | ||
// @ts-ignore | ||
import inject from 'rollup-plugin-inject'; | ||
import { builtinsResolver, NodePolyfillsOptions } from './modules'; | ||
import { dirname, relative } from 'path'; | ||
import { randomBytes } from 'crypto'; | ||
|
||
export default function (opts: NodePolyfillsOptions = {}) { | ||
const injectPlugin = inject({ | ||
'process': 'process', | ||
'Buffer': ['buffer', 'Buffer'], | ||
'global': require.resolve('../polyfills/global.js'), | ||
'global': GLOBAL_PATH, | ||
'__filename': FILENAME_PATH, | ||
'__dirname': DIRNAME_PATH, | ||
}); | ||
const basedir = opts.baseDir || '/'; | ||
const dirs = new Map<string, string>(); | ||
const resolver = builtinsResolver(opts); | ||
return { | ||
...injectPlugin, | ||
name: 'node-polyfills', | ||
resolveId(importee: string) { | ||
resolveId(importee: string, importer: string) { | ||
if (importee === DIRNAME_PATH) { | ||
const id = getRandomId(); | ||
dirs.set(id, dirname('/' + relative(basedir, importer))); | ||
return id; | ||
} | ||
if (importee === FILENAME_PATH) { | ||
const id = getRandomId(); | ||
dirs.set(id, dirname('/' + relative(basedir, importer))); | ||
return id; | ||
} | ||
return resolver(importee); | ||
}, | ||
load(id: string) { | ||
if (dirs.has(id)) { | ||
return `export default '${dirs.get(id)}'`; | ||
} | ||
} | ||
}; | ||
} | ||
|
||
function getRandomId() { | ||
return randomBytes(15).toString('hex'); | ||
} | ||
|
||
const GLOBAL_PATH = require.resolve('../polyfills/global.js'); | ||
const DIRNAME_PATH = '\0node-polyfills:dirname'; | ||
const FILENAME_PATH = '\0node-polyfills:filename'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters