17

I am creating a React.js app in which I am getting the stack trace like this:

let trace = new Error().stack;

The app was created using create-react-app

When sending the trace to a server, I get these kind of lines:

at onBlur (http://localhost:3000/static/js/main.chunk.js:538:82)

At the line above, the onBlur is correct, but the file name is not.

Is there a way to get the name of the files as they are named in my project instead of main.chunk.js (which I assume is a compiled file created by webpack)?

Daniele Ricci
  • 15,422
  • 1
  • 27
  • 55
CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • Do you have source map generation disabled? You should already see file mapping for production builds. See https://stackoverflow.com/questions/55904292/how-to-generate-sourcemaps-in-create-react-app – isherwood Dec 01 '20 at 19:58
  • didn't know of something called a "source map" before your comment so no, i didn't disable it – CodeMonkey Dec 02 '20 at 19:59
  • @YonatanNir What version of `react-scripts` do you have in package.json and did you start it with `react-scripts start` (usually known as `start` in package.json scripts)? – HMR Dec 04 '20 at 11:37

1 Answers1

5

You can use npm package craco - craco will allow you to specify webpack options without needing to eject the react application.

You can specify option devtool to control source code here is craco.config.js file to preserve line numbers

module.exports = {
    webpack: {
      
        configure: {
            
            devtool: 'eval-source-map'

    }
    }
}

and you need to update package.json start script to

"start": "craco start"


function App() {

  function handleClick(e) {
    e.preventDefault();
    let trace = new Error().stack;
    console.log('The link was clicked.' , trace);
  }

return (
        <button onClick={handleClick} > Blur</button>
)
}

You will see that original line number and file name are preserved.

enter image description here

Meera Datey
  • 1,913
  • 14
  • 15