Skip to content

Commit

Permalink
feat(): support for __dirname and __filename
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat committed Jun 6, 2019
1 parent f796e4d commit 9fb7678
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export default {
input: 'dist-transpiled/index.js',
external: [
'path',
'crypto',
'rollup-plugin-inject'
],
output: [
Expand Down
33 changes: 31 additions & 2 deletions src/index.ts
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';
1 change: 1 addition & 0 deletions src/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const EMPTY_PATH = require.resolve('../polyfills/empty.js');
export interface NodePolyfillsOptions {
fs?: boolean;
crypto?: boolean;
baseDir?: string;
}

export function builtinsResolver(opts: NodePolyfillsOptions) {
Expand Down

0 comments on commit 9fb7678

Please sign in to comment.