Skip to content
This repository has been archived by the owner on Apr 11, 2024. It is now read-only.

Add a guide on how to import Benchmark with a module bundler #237

Open
pckhoi opened this issue Dec 23, 2020 · 1 comment
Open

Add a guide on how to import Benchmark with a module bundler #237

pckhoi opened this issue Dec 23, 2020 · 1 comment

Comments

@pckhoi
Copy link

pckhoi commented Dec 23, 2020

My general feeling about this package is that it feels like it has been created 20 years ago. No UMD module, strange export mechanism, there's a single source file which is a giant hairball of 2000+ lines of code... It is very unfriendly to the modern JavaScript development stack.

So I've only tried with Rollup but it has been quite hard to bundle Benchmark into something that can run in the browser. Thought you might be interested in including this little wrapper for those who are using module bundler:

TypeScript:

import _ from 'lodash'
import Benchmark from 'benchmark'

// avoid `Cannot read property 'parentNode' of undefined` error in runScript
const script = document.createElement('script')
document.body.appendChild(script)

// Benchmark could not pick up lodash otherwise
const bm: any = Benchmark.runInContext({ _ })

// avoid `ReferenceError: Benchmark is not defined` error because Benchmark is assumed to be in window
const win = window as any
win.Benchmark = bm

export default bm

ES2015:

import _ from 'lodash'
import Benchmark from 'benchmark'

// avoid `Cannot read property 'parentNode' of undefined` error in runScript
const script = document.createElement('script')
document.body.appendChild(script)

// Benchmark could not pick up lodash otherwise
const bm = Benchmark.runInContext({ _ })

// avoid `ReferenceError: Benchmark is not defined` error because Benchmark is assumed to be in window
window.Benchmark = bm

export default bm
@davidenke
Copy link

Just a little Typescript alternative without the anys:

import _ from 'lodash';
import Benchmark from 'benchmark';

// declare the global property
declare global {
  interface Window {
    Benchmark: typeof Benchmark;
  }
}

// avoid `Cannot read property 'parentNode' of undefined` error in runScript
const script = document.createElement('script');
document.body.appendChild(script);

// cast the faulty `Function` type
window.Benchmark = Benchmark.runInContext({ _ }) as typeof Benchmark;

// provide scoped constructor
export default window.Benchmark;

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants