Vien Nguyen
Vien Nguyen

Reputation: 385

How to enable source maps in create-react-app?

everyone.

I am a new member of react and I created my app use create-reat-app .I used node-sass-chokidar package like react's document. But I don't know how to enable "source maps" of scss file.

Thanks for any help.

Upvotes: 10

Views: 30459

Answers (7)

Muhammad Abdullah
Muhammad Abdullah

Reputation: 4485

Note: To enable SourceMap just simply set following to true or false as:

To enable:

"scripts": { 
    "build": "set  \"GENERATE_SOURCEMAP=true\" && react-scripts build" 
  }

To disable:

"scripts": { 
    "build": "set  \"GENERATE_SOURCEMAP=false\" && react-scripts build" 
  }

Important:

GENERATE_SOURCEMAP does not have effect in development mode, only works for production

Upvotes: 2

cjn
cjn

Reputation: 1451

I had the same error using create-react-app and was worried I would have to eject, but turns out that's not the case. The create-react-app docs show it's supported and even list the steps to analyze your app's build using source-map-explorer like this (my paraphrase summary with "gatcha" case):

  1. Install the source-map-explorer (I saved into devDependencies, but you could remove --only=dev to save into primary dependencies like create-react-app docs):

    $ npm install --save --only=dev source-map-explorer
    

    OR if you use yarn...

    $ yarn add source-map-explorer
    
  2. Then in package.json, add the the "analyze" named script:

    "scripts": {
      ...
      "analyze": "source-map-explorer 'build/static/js/*.js'",
    },
    
  3. [OPTIONAL/"gatcha"] This is an optional step depending on how you have create-react-app configured, but my production configuration was preventing the sourcemap from being built, so I was getting an error of the type:

    Unable to find a source map.
    See https://github.com/danvk/source-map-explorer/blob/master/README.md#generating-source-maps

    To fix that, I had to REMOVE a line TEMPORARILY from the .env.production configs so I could generate the production build WITH the sourcemaps for analyzing. The following line needed to be removed from my .env.production:

    GENERATE_SOURCEMAP=false
    
  4. Next, we need to re-build the production build (including sourcemap generation) so that we have something to analyze. If you built before now, you may need to rebuild again now (especially if sourcemap generation was disabled), so better safe than sorry - just rebuild again now.

    $ npm run build
    
  5. [OPTIONAL/"gatcha"] If you removed the GENERATE_SOURCEMAP=false line from .env.production, now is the time to RE-add it back into your .env.production config now (I recommend doing it now, so you don't get distracted & forget to add it back! You can always temp take it out again if you need to adjust & re-build with sourcemap, but it's easy to forget to return temp things like this.)

  6. Now, you are ready to review the source-map-explorer's analysis via the normal source-map-explorer script we added in step 2.

    $ npm run analyze
    

You should now be seeing those results for your create-react-app in a non-ejected state.

Upvotes: 1

yaya
yaya

Reputation: 8243

(Note: Generally changing stuffs inside node_modules is bad. you better to eject it first with yarn eject.)

For me adding sourceMap: true option worked.

Details: On this file: node_modules\react-scripts\config\webpack.config.js, edit :

{
  loader: require.resolve('css-loader'),
  options: {...cssOptions, sourceMap: true,}, // <-- sourceMap: true added to css-loader options
},

Ps: if you manually use other loaders like sass-loader and postcss-loader, make sure to add sourceMap: true option for all of them.

Upvotes: 0

Yugandhar Pathi
Yugandhar Pathi

Reputation: 964

I am using create-react-app and this is how I Fixed it (without running eject cmd)

Note : 1. Below solution will help to load *.js.map files.
2. If your app is already overriding webpack config using react-app-rewired you can ignore first three steps.

  1. npm i react-app-rewired -D - This will help you to override webpack configuration.
  2. package.json - change your scripts, replace react-scripts with react-app-rewired
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  }

  1. config-overrides.js - create this file in the parent level of the app.

  2. npm i source-map-loader -D - To load source maps (assuming that your lib's dist has source map file). It doesn't matter which build tool(ex: Rollup, webpack or parcel) you use to generate sourcemap.

  3. Copy below code in config-overrides.js

module.exports = {
  webpack: (config, env) => {
    // Load source maps in dev mode
    if (env === 'development') {
      config.module.rules.push({
        test: /\.(js|mjs|jsx|ts|tsx)$/,
        use: ['source-map-loader'],
        enforce: 'pre',
      });

      // For `babel-loader` make sure that sourceMap is true.
      config.module.rules = config.module.rules.map(rule => {
        // `create-react-app` uses `babel-loader` in oneOf
        if (rule.oneOf) {
          rule.oneOf.map(oneOfRule => {
            if (
              oneOfRule.loader &&
              oneOfRule.loader.indexOf('babel-loader') !== -1
            ) {
              if (oneOfRule.hasOwnProperty('options')) {
                if (oneOfRule.options.hasOwnProperty('sourceMaps')) {
                  // eslint-disable-next-line no-param-reassign
                  oneOfRule.options.sourceMaps = true;
                }
              }
            }
          });
        }
        return rule;
      });
    }

    return config;
  },
};


  1. Restart your app (if it's already running). source files get loaded in different locations, based on path in map file. Check all folders patiently :)

Note : 1. Your source maps get loaded in one of the folder(ex : localhost:3000 or webpack:/// ) based on path it reads from xxx.js.map file. 2. If you are using rollup for your libs, please make sure you give proper path in the configuration file (output.sourcemapPathTransform ), This will help to load sourcemaps in the proper location.

Upvotes: 1

cleverettgirl
cleverettgirl

Reputation: 71

Update to their newest react-scripts (2.1.5). They've recently added support for this: https://github.com/facebook/create-react-app/pull/5713

Upvotes: 4

MStodd
MStodd

Reputation: 4746

Add the "--source-map" option with the value "true" as in the example below:

node-sass-chokidar --source-map true --include-path ./node_modules src/styles/scss -o src/styles/css

Upvotes: -1

Ruslan Zaytsev
Ruslan Zaytsev

Reputation: 444

there are several ways to achieve source mapping with create-react-app, but as far as I know - in any case, you need to edit config of webpack. Configs and scripts for npm cli commands (start, build, eject) are stored in a package called 'react-scripts'. There are two ways to access them:

option A) eject your project by running $ yarn eject. This will unwrap all related dependencies into your project package.json and also dirs from react-scripts package named config and scripts into a root of your project.

option B) Make your own custom react-scripts package (or use someone's). In this case, you don't have to eject from a project and your project will be clean. This way you can replace default 'react-scripts' with your own.

yarn remove react-scripts
yarn add <your-custom-react-scripts>

try mine if you wish - rulsky-react-scripts - it comes with sass processing (with sourcemaps enabled) and browsersync.

Either way, you have to add node-sass and sass-loader into dependency graph (but in different places).


Next steps I'll highlight how to add sorceMap by ejecting project and assume you have yarn (because with CRA it is better to use yarn). All paths are relative to root of your project

1) yarn eject

2) yarn add node-sass sass-loader

3) open config/webpack.config.dev.js

4) in module.rules edit excudions for file-loader of style files ````

-  /\.css$/,
+  /\.(css|scss|sass)$/,

````

5) in 'style-related chain of loaders' expand 'test' property: ````

-  test: /\.css$/,
+  test: /\.(css|scss|sass)$/,

````

6) add to options of 'css-loader' property sourceMap: true,. It should look like so: ````

{
 loader: require.resolve('css-loader'),
  options: {
   importLoaders: 1,
   sourceMap: true,
  },
},

````

7) right after 'css-loader' add 'sass-loader' with appropriate options: ````

{
 loader: require.resolve('sass-loader'),
  options: {
   sourceMap: true,
  }
},

````

8) Now we need to edit production configuration of webpack.

9) open config/webpack.config.prod.js and make the same changes to it: file-loader exclusions and style-related chain of loaders.

Upvotes: 3

Related Questions