Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create-react-app sass sourcemaps not working #5707

Closed
mustafaabobakr opened this issue Nov 4, 2018 · 56 comments · Fixed by #8638
Closed

create-react-app sass sourcemaps not working #5707

mustafaabobakr opened this issue Nov 4, 2018 · 56 comments · Fixed by #8638

Comments

@mustafaabobakr
Copy link

Sass sourcemaps shows only on yarn build

Can we have sourcemaps enabled by default in development ! yarn start

Environment

Node: v11.1.0
yarn: v1.12.1
npm: v6.4.1
Chrome: v70

image

image

alicialics pushed a commit to alicialics/create-react-app that referenced this issue Nov 5, 2018
@stale
Copy link

stale bot commented Dec 5, 2018

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Dec 5, 2018
@Syden10
Copy link

Syden10 commented Dec 7, 2018

Any estimate for an official fix on this? Thanks.

@stale stale bot removed the stale label Dec 7, 2018
@mustafaabobakr
Copy link
Author

Any Updates on this ?
Is there a working workaround ?

@BenAttenborough
Copy link

I suspect the team isn't moving particularly fast on this (btw team you are doing an excellent job!), because the react approach favours component level styling over a sass approach. However if sass is being support then source maps probably should be too. I'd certainly find it useful!

@kuangthien
Copy link

Anybody have temporarily solution ? :(

@agairing
Copy link

agairing commented Dec 25, 2018

The following did work for me:

  • open node_modules\react-scripts\config\webpack.config.js
  • replace "isEnvProduction" with "isEnvDevelopment" for the css-loader, css-module loader, sass loader and sass module loader (between lines 443 - 500)
  • start development process with "npm start"
    grafik

@NotAmaan
Copy link

The following did work for me:

  • open node_modules\react-scripts\config\webpack.config.js
  • replace "isEnvProduction" with "isEnvDevelopment" for the css-loader, css-module loader, sass loader and sass module loader (between lines 443 - 500)
  • start development process with "npm start"

@agairing Those changes would be lost on every npm install so I would advice against ever editing anything inside node_modules

@agairing
Copy link

@NotAmaan Right. It's just intended as a temporary solution (if you need working source maps - like myself....).

@danieltodonnell
Copy link

bump.

@clubajax
Copy link

clubajax commented Jan 4, 2019

I tried the solution from @agairing - but the source maps all point to main.scss and not the individual scss files. So there is still something missing.

[edit] process.env.GENERATE_SOURCEMAP needed to be set to true.

@agairing
Copy link

agairing commented Jan 4, 2019

I just saw, that there are also 2 more spots in the "webpack.config.js" configuration file where I did replace isEnvProduction with isEnvDevelopment:
grafik

@Syden10
Copy link

Syden10 commented Jan 16, 2019

Thanks @agairing for the workaround suggestion.
As @NotAmaan pointed out, this would be lost on npm install, so not ideal on my end.

Could anyone share some light on whether an official fix is being considered? Would be much appreciated (even if later than sooner, but at least to know if it will be officially fixed eventually)

Also, I've created the following SO post a while back, just in case anyone wanna jump in:
https://stackoverflow.com/questions/53450140/create-react-app-sass-source-maps-not-working

Thank you.

@ianschmitz
Copy link
Contributor

@Syden10, we have #5713 that should fix this.

@mustafaabobakr
Copy link
Author

@ianschmitz
THANK YOU
Will it be available in next release ? or is it available now !

@Syden10
Copy link

Syden10 commented Jan 17, 2019

@ianschmitz Thanks so much for the reply!

Tried updating to 2.1.3 yesterday but still wasn't working, would be up on next release?

@ianschmitz
Copy link
Contributor

Please follow #5713 for updates.

@Syden10
Copy link

Syden10 commented Jan 17, 2019

Will do, thanks again.

@bugzpodder
Copy link

This is fixed in the latest release.

@lock lock bot locked and limited conversation to collaborators Feb 16, 2019
@bugzpodder
Copy link

This will be reverted because of #6399.

@bugzpodder bugzpodder reopened this Feb 20, 2019
@facebook facebook unlocked this conversation Feb 22, 2019
@Shaker-Hamdi
Copy link

Any news on this?

@armaanahluwalia
Copy link

Are there any updates on this? This seems to still be an issue on Chrome even with CRA 3.0.0

@Syden10
Copy link

Syden10 commented Jul 1, 2019

Seems the PR above (#7114) is closed now, just posted to see if we can bring attention back to it.

After 8 months, an official word on this would be appreciated, if there is no interest in providing a fix in the short term, please make us aware.

Thank you.

@bugzpodder
Copy link

Thanks for being patient and sorry for the slowness. Personally I'm not keen on providing a solution that would cause issues when turned on even when it's behind a flag. People would just raise more issues against these problems. If you really need this feature you can use a third party solution like react-app-rewired.

@Syden10
Copy link

Syden10 commented Jul 2, 2019

Jack thanks so much for the reply!

Just to clarify from your post, a fix without breaking other stuff would not be feasible?
Also sorry for the ignorance, but how come it was working accordingly on older versions?
Has a proper fix for this issue been considered by the team at some point at all?

Thanks again.

@bugzpodder
Copy link

We've attempted to release this change before, it isn't that it doesn't work (it does), but turns out it causes other significant problems like FOUC and perf degrading. If we release the same change behind a flag, these issues will inevitably be raised again.

@armaanahluwalia
Copy link

@bugzpodder Could you point to an upstream bug thats causing this? We could keep an eye on that to look for when it could be merged in. Source map support is one of those basic things that any web application development framework, plugin or tool should support. If it is not supported, it should be clearly mentioned in the README somewhere so people are sure what they're investing their personal/company resources in and how painful it would be to work with, don't you think?

@bugzpodder
Copy link

bugzpodder commented Jul 2, 2019

Once other problems like #6399 no longer manifests we will revisit this issue. Currently I am not aware of any upstream PRs that would fix any of these problems.

@mustafaabobakr
Copy link
Author

@bugzpodder
Can you please show an example of How to use react-app-rewired to enable sourcemaps ?

@bugzpodder
Copy link

@mostafaabobakr7 See #5707 (comment)

@Oxygen66
Copy link

Any estimate for an official fix on this? Thanks. (CRA 3.0.1)

@Jonathan0wh
Copy link

@Oxygen66

I have been waiting for this to be resolved for more than half a year... Before it was resolved, we will always have to use the workaround here, but still, it is just a workaround, so it would still be better if there is an official solution as soon as possible.

This issue depends on #5707 (comment), which seems to be... promising in their 3.1 milestone (not sure about it)?

@jonathantneal
Copy link

jonathantneal commented Jul 21, 2019

Hi all! I think I know what is going on and how to fix it.

Background

The ability to enable source maps during development was originally added in #5713 and released in v2.1.4. Unfortunately, enabling source maps during development caused a flash of unstyled content (FOUC), which was reported in #6399. To resolve that issue, support for source maps during development was removed in #6399 and released in v2.1.6.

Cause

The FOUC occured because JS rendered before CSS. JS rendered before CSS because style-loader injected <link> tags instead of <style> tags whenever source maps were enabled, and <link> tags render asynchronously when injected with JS.

Faulty Workaround

So, why ever inject <link> tags instead of <style> tags? That technique was originally used to work around a bug that preventing source maps in <style> tag from working in Chrome, but that bug was fixed in 2015.

This is why the <link> workaround was removed from style-loader in 2017, and also removed from vue-style-loader in 2016. Unfortunately, the removal never made it into the master branch of style-loader, mostly likely due to a mistake in branch management.

Solution

The solution, I hope, is to share this history with the style-loader team and submit a PR to restore the original fix.

And here it is! webpack-contrib/style-loader#383

@bugzpodder
Copy link

@jonathantneal that's awesome! Appreciate your effort here and hopefully we can find a resolution for this soon!

@jonathantneal
Copy link

A couple updates

  1. I am working with a maintainer of style-loader to get this merged very soon, and I am told that it is now prioritized.

  2. Good news; this change will incidentally reduce repaints, which should improve performance during development.

    For instance, I enabled paint flashing in order to see if there would be any impacts from switching from the Link Blob (<link href=CSSBLOB />) strategy to the Inline Style <style>CSS</style> strategy.

    When I changed the color of some text, the Link Blob strategy sometimes caused the text and any of its containers affected by the same style sheet to unnecessarily repaint. When using the Inline Style strategy, only the text was repainted, and there were no additional, unnecessary repaints. 😄

@devinrhode2
Copy link

devinrhode2 commented Aug 21, 2019

I have an updated version of @zaderac's craco snippet. Enables /* line 88, src/app/foo.scss */ comments in sourcemaped css output. Here's my craco.config.js:

module.exports = {
  plugins: [{
      plugin: require('craco-plugin-react-hot-reload')
    },
    {
      // "craco-plugin-sass-sourcemaps" inline https://github.com/facebook/create-react-app/issues/5707#issuecomment-503614767
      plugin: {
        overrideWebpackConfig: ({
          webpackConfig,
          cracoConfig,
          pluginOptions,
          context: {
            env,
            paths
          }
        }) => {
          function traverse(obj, callback) {
            if (Array.isArray(obj)) {
              obj.forEach(item => traverse(item, callback));
            } else if (typeof obj === 'object' && obj !== null) {
              Object.keys(obj).forEach(key => {
                if (obj.hasOwnProperty(key)) {
                  callback(obj, key);
                  traverse(obj[key], callback);
                }
              });
            }
          }

          traverse(webpackConfig, (node, key) => {
            if (key === 'loader') {
              if (
                node[key].indexOf('sass-loader') !== -1 ||
                node[key].indexOf('postcss-loader') !== -1 ||
                node[key].indexOf('css-loader') !== -1
              ) {
                if (node.options) {
                  if (node[key].indexOf('sass-loader') !== -1) {
                    // adds /* line 88, src/app/foo.scss */ comments in sourcemaped css output
                    node.options.outputStyle = 'expanded';
                    node.options.sourceComments = true;
                    node.options.outFile = './css/theme.css';
                  }
                  node.options.sourceMap = true;
                }
              }
            }
          });

          return webpackConfig;
        }
      }
    }
  ],
  eslint: {
    // make cra read .eslintrc file
    mode: require('@craco/craco').ESLINT_MODES.file,
    loaderOptions: {
      // with this formatter with iTerm2/Guake/etc you can cmd+click
      // eslint warnings and it's open the file in your editor at the
      // specified line number!
      formatter: require('eslint-formatter-compassion')
      // eslint-formatter-friendly is also awesome
    }
  }
};

@heyimalex
Copy link
Contributor

We merged style-loader in #7473, so I think we may be able to re-try merging #5713. Anyone interested should give it a shot.

@PsiRadish
Copy link

So to officially move this forward does someone need to make a pull request that re-applies the changes from #5713?

@armaanahluwalia
Copy link

@zhuoli99 Would you consider resending your PR to fix this issue? Can be quite a pain for quite a lot of people.

@PsiRadish
Copy link

Would it violate any etiquette/rules (spoken or unspoken) if someone besides @zhuoli99 made a pull request that re-applies the changes from #5713?

@heyimalex
Copy link
Contributor

@PsiRadish No, you're fine, just validate that the issue that caused it to be reverted is actually fixed! I'll commit to reviewing :)

AlexanderPPetrov added a commit to AlexanderPPetrov/js-client-react that referenced this issue Dec 23, 2019
@ljosberinn
Copy link
Contributor

Alternatively, you may use this script to manipulate the webpack config - doesn't require CRACO or its huge config.

  • add this script to scripts/enable-css-sourcemaps.js
const { writeFileSync, existsSync, readFileSync } = require('fs');

const path = 'node_modules/react-scripts/config/webpack.config.js';

const find = /(sourceMap: isEnvProduction && shouldUseSourceMap)/g;
const replace = 'sourceMap: isEnvDevelopment && shouldUseSourceMap';

if (existsSync(path)) {
  const buffer = readFileSync(path)
    .toString()
    .replace(find, replace);

  try {
    writeFileSync(path, buffer);
    console.info('enable-css-sourcemaps: active');
  } catch (e) {
    console.error(`enable-css-sourcemaps: ${path} manipulation failed!`);
  }
} else {
  console.warn(`enable-css-sourcemaps: ${path} does not exist`);
}
  • add this script to your package.json scripts:
    "postinstall": "node ./scripts/enable-css-sourcemaps.js"

@jitendrasaroj93
Copy link

jitendrasaroj93 commented Jan 27, 2020

I think i found the issue in react-script\config\webpack-config.js
Line 503,517, 532 and 549 of style-loaders options:
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See webpack/webpack#6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See webpack/webpack#6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you import an asset, you get its (virtual) filename.
// In production, they would get copied to the build folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude js files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude html and json extensions so they get processed
// by webpacks internal loaders.
exclude: [/.(js|mjs|jsx|ts|tsx)$/, /.html$/, /.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},

sourcemaps never get enabled in developement environement.
why **shouldUseSourceMap** variable isn't enough for sourcemaps control?
FIX:
modify those lines as:
sourceMap: shouldUseSourceMap
just get rid of isEnvProduction.

@MKorostoff
Copy link
Contributor

Hey, seems like there hasn't been any action on this thread in a while. I just submitted a PR with (I think) the changes discussed above #8638

@birkmann
Copy link

I think i found the issue in react-script\config\webpack-config.js
Line 503,517, 532 and 549 of style-loaders options:
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See webpack/webpack#6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See webpack/webpack#6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you import an asset, you get its (virtual) filename.
// In production, they would get copied to the build folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude js files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude html and json extensions so they get processed
// by webpacks internal loaders.
exclude: [/.(js|mjs|jsx|ts|tsx)$/, /.html$/, /.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},

sourcemaps never get enabled in developement environement.
why **shouldUseSourceMap** variable isn't enough for sourcemaps control?
FIX:
modify those lines as:
sourceMap: shouldUseSourceMap
just get rid of isEnvProduction.

This fixed it for me for the moment. How can i avoid this problem in future projects?

@lock lock bot locked and limited conversation to collaborators May 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.