Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Vien Nguyen Avatar asked May 08 '17 07:05

Vien Nguyen


2 Answers

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.

like image 145
Ruslan Zaytsev Avatar answered Sep 30 '22 19:09

Ruslan Zaytsev


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

like image 21
cleverettgirl Avatar answered Sep 30 '22 19:09

cleverettgirl