ReferenceError: performance is not defined when using performance.now()
I know this is tagged front-end but if anyone comes across this looking for a node.js solution (like me), you need to first require performance from the perf_hooks module (available in node 8.5+).
const {performance} = require('perf_hooks');
const t0 = performance.now();
...
Since the 'perf_hook' module exports multiple constructs (objects, functions, constants, etc.), you will need to explicitly specify which construct you wish to use. In this case, you need the performance
construct. The declaration can be done in two ways:
const performance = require('perf_hooks').performance;
or
const { performance } = require('perf_hooks'); //object destructuring
You will lose type information when using require
, so the best way to import "performance" with TypeScript is using an import
statement:
import {performance, PerformanceObserver} from 'perf_hooks';
const observer = new PerformanceObserver(items => items.getEntries().forEach((entry) => console.log(entry)));
observer.observe({entryTypes: ['measure']});
performance.mark('start');
performance.mark('stop');
performance.measure('Measurement', 'start', 'stop');
Also make sure that you declared @types/node
in your "dependencies" of "package.json".
Tested with TypeScript 4 & Node.js 14.