Unable to resolve module `perf_hooks`
Asked Answered
D

3

7

I am trying to use perf_hooks from the nodeJS Performance API in my React Native project. Below is my code

import {performance} from 'perf_hooks';

export const measure = (
  target: Object,
  propertyKey: string,
  descriptor: PropertyDescriptor
) => {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args) {
    const start = performance.now();
    const result = originalMethod.apply(this, args);
    const finish = performance.now();
    console.log(`Execution time: ${finish - start} milliseconds`);
    return result;
  };

  return descriptor;
};

I keep getting the same error. error: bundling failed: Error: Unable to resolve module perf_hooks from src/utils/metrics.ts: perf_hooks could not be found within the project.

Performance API is available from node version 8.x and my node -v response is 10.16.1.

I see that there is perf_hooks present in my node_modules as well under the @types/node/perf_hooks folder.

Doggery answered 12/8, 2020 at 19:11 Comment(3)
There are lots of platform facilities provided as module by the NodeJS runtime. This isn't a NodeJS app, is it?Leyte
You are right. This isn't a nodeJS application, it's a react native app. But I see that the node_modules contains the perf_hooks folder which means that nodeJS utilities are available. But I'm unable to use them.Doggery
Hmm that should work then or at least the error should be different.Leyte
P
4

First import node types

$ npm i --save-dev @types/node

Now change the import statement to this:

import { performance } from 'perf_hooks';
Pauiie answered 12/9, 2021 at 8:27 Comment(1)
Note that I copied code from node.js docs that used const { performance } = require('perf_hooks'). Took me a while until I realised this. I changed to import and the types started working.Pepper
E
3

Update / upgrade your node version and try a fresh install. This should solve the issue.

Ephemerality answered 9/11, 2022 at 20:53 Comment(0)
R
0

For react-native, use react-native-performance.

It's an implementation of the Performance API for React Native.

Rotz answered 5/6, 2024 at 22:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.