Angular-cli: Source map not working for SCSS files

Created on 5 Jan 2018  Â·  87Comments  Â·  Source: angular/angular-cli

Recently I updated cli version 1.3.2 to 1.6.3 and after that I can't see scss source mapped file in developer tools in Chrome of Firefox .

Versions : 1.6.3

Angular CLI: 1.6.3
Node: 8.9.3
OS: win32 x64
Angular: 5.0.0
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

@angular/cli: 1.6.3
@angular/language-service: 4.4.6
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.3
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.4.2
webpack: 3.10.0

Repro steps

  • Create new angular app using ng new sample-app
  • Add scss file in angular-cli.json "styles": ["styles/styles.scss"]
  • Launch app using ng serve -sm -ec
  • Inspect styles using chrome dev-tools.

Observed behavior

No actual scss file, only style.bundle.css where all the styles compiled.
image

Desired behavior

Actual scss file can be seen in the developer tools with the line number
image

2 (required) bufix

Most helpful comment

works for me using version 6.0!!

solution:

  1. modify angular.json to add __--extract-css, in 6.0 this argument is removed from ng serve__
 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
           ---
          },
          "configurations": {
            "production": {
              ---
            },
            "serve": {
              "extractCss": true,
               ---
            }
          }
        },

hen change _serve->options->browserTarget->project-name:build_ to _project-name:build:serve_

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "open": true,
            "browserTarget": "<project-name>:build:serve"
          },
          "configurations": {
            "production": {
              ---
            }
          }
        }
  1. run
    ng serve --source-map
    image

All 87 comments

@clydin any update on this?

Source map not working for LESS files

I have the same issue with Less files too.

The component LESS files appear, but the styles brought in via the CLI are not.

Versions

Angular CLI: 1.6.2
Node: 6.11.2
OS: darwin x64
Angular: 5.1.2
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.6.2
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.40
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.2
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.10
typescript: 2.4.2
webpack: 3.10.0

Dnia 5 stycznia 2018 04:42 Rukshan Lakshitha Dangalla <[email protected]> napisaÅ‚(a): Recently I updated cli version 1.3.2 to 1.6.3 and after that I can't see scss source mapped file in developer tools in Chrome of Firefox . Versions : 1.6.3 Angular CLI: 1.6.3Node: 8.9.3OS: win32 x64Angular: 5.0.0... animations, common, compiler, compiler-cli, core, forms... http, platform-browser, platform-browser-dynamic... platform-server, router@angular/cli: 1.6.3@angular/language-service 4.4.6@angular-devkit/build-opt 0.0.36@angular-devkit/core: 0.0.22@angular-devkit/schemati 0.0.42@ngtools/json-schema: 1.1.0@ngtools/webpack: 1.9.3@schematics/angular: 0.1.11@schematics/schematics: 0.0.11typescript: 2.4.2webpack: 3.10.0 Repro steps Create new angular app using ng new sample-app Add scss file in angular-cli.json "styles": ["styles/styles.scss"] Launch app using ng serve -sm -ec Inspect styles using chrome dev-tools. Observed behavior No actual scss file, only style.bundle.css where all the styles compiled. zasobygwp.pl Desired behavior Actual scss file can be seen the developer tools with the line number zasobygwp.pl — You are receiving this because you are subscribed to this thread. Reply to this email directly, zasobygwp.pl view it on GitHub , or zasobygwp.pl mute the thread .

I've found that it is actually working for me, but just not for Bootstrap.

We're building bootstrap manually and therefore not using the default bootstrap.less found in the LESS folder.

It does not show references to my project's scss files nor to bootstrap 4's scss files. Only to styles.bundle.css.

My issues is with Bootstrap 3 and LESS

I've got a bootstrap.less (copy from ~/bootstrap/less/bootstrap.less) in my app folder that I've added to the angular-cli.json

Which when I run ng serve -sm -ec -env=mock shows source maps for my components but not for my complied global less files imported from the angular-cli.json

So the fix they mention about removing ~ will not work for me...

I am not even using ~ we use:

      "styles": [
        "../node_modules/prismjs/themes/prism.css",
        "../node_modules/@ngx-loading-bar/core/loading-bar.css",
        "../node_modules/ng2-toastr/bundles/ng2-toastr.min.css",
        "sass/designsystem/designsystem.scss",
        "styles.scss"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.slim.js",
        "../node_modules/popper.js/dist/umd//popper.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js"
      ],

The css is complied and works for all of these, but no source maps.

@smlombardi Yeah, seems like a bug from at least 1.6.2 onwards

I've had this problem from 1.5 onwards

As I can see many folks have this issue. What can we do about this?

1.6.5 didn't solve the issue for me. (LESS)

This is making it very hard to work and debug css styling issues.

Same issue here when I upgraded from 1.4.7 to 1.6.5. Please fix, this is a major blocker!

Still not working in 1.6.6, FWIW.

I have same issue, and still wait for fixing. This is a critical issue, it blocks rapid development.

This is main reason why I am still using Angular 4 and cli 1.4.x in production and not upgrading to Angular 5.

Some Context:

  • using angular-cli version 1.6.6
  • project is generated by the CLI.
  • using Scss

I remembered it was a weird thing in Webpack config where I had to add extra config to allow sourcemap (in addition to the plugin config).

Solution:
In "node_modules\@angular\cli\models\webpack-configs\common.js" file, in line 162, Add a line devtool: 'source-map', in the returned common configuration object in the getCommonConfig function, e.g.

    ...
    catch (e) { }
    return {
        devtool: 'source-map',        // add this line
        resolve: {
            extensions: ['.ts', '.js'],
             ...

Tested with the following Commands in terminal (also works with Sass @import):

ng serve           // no sourcemap
ng serve -sm -ec   // has sourcemap
ng serve --sourcemap --extract-css  // has sourcemap   
ng serve --sourcemap --extractCss   // has sourcemap   

@chaeusler Not working for me, 1.6.7

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.resolve has an unknown property 'devtool'. These properties are valid:
   object { alias?, aliasFields?, cachePredicate?, cacheWithContext?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }

Proposed solution by @CharltonC works for me on v1.6.3 and v1.6.7 (two test projects I happen to have now). I am using scss @imports for bootstrap and material in styles.scss and I have proper source maps now. Exactly what I need. Thanks CharltonC!

@chaeusler @dmijatovic Am I missing something? When I add the line recommended, I get the above error, in short configuration.resolve has an unknown property 'devtool'

This is a standard install of 1.6.7

@smlombardi, it looks like your devtool definition is not at right level of configuration. Examine the structure of return {...} @CharltonC provided. The exact line number in the common.js file may vary. I hope this helps.

@CharltonC thanks for the workaround. Can we expect any kind of fix from the angular team?

@CharltonC It worked for me.

CSS Preprocessor: LESS

Version:

Angular CLI: 1.6.5
Node: 6.11.2
OS: darwin x64
Angular: 5.2.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.6.5
@angular-devkit/build-optimizer: 0.0.41
@angular-devkit/core: 0.0.28
@angular-devkit/schematics: 0.0.51
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.5
@schematics/angular: 0.1.16
typescript: 2.6.2
webpack: 3.10.0

@smlombardi You have entered the line in the wrong place.

This is where I imagine you have placed it:

return {
  resolve: {
    devtool: 'source-map',
    ...
  }
}

in needs to be in the return object one level higher:

return {
  devtool: 'source-map',
  resolve: { ... },
  ...
}

@michael-letcher Thanks. missed that. I confirm it's working now for scss.

Glad it works for everyone. Cheers.

it works. but why angular cli not add it?

Issue still present in v1.7.0
The workaround DOES NOT WORK in v1.7.0!

Edit: Not sure why down voted, the work around does not work for me anymore when using CLI v1.7.0

Angular CLI: 1.7.0
Node: 6.11.2
OS: darwin x64
Angular: 5.2.5
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.7.0
@angular-devkit/build-optimizer: 0.3.1
@angular-devkit/core: 0.3.1
@angular-devkit/schematics: 0.3.1
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.0
@schematics/angular: 0.3.1
@schematics/package-update: 0.3.1
typescript: 2.6.2
webpack: 3.11.0

I create such file as postinstall can patch it.
inspired from angular aio https://github.com/angular/angular/tree/master/aio/tools/cli-patches

in your project create following files

tools/cli-patches/patch.js

const fs = require('fs');
const sh = require('shelljs');

const PATCH_LOCK = 'node_modules/@angular/cli/models/webpack-configs/.patched-webpack-enable-sourcemap';

//can generate patch file by `git diff` or use `diff -Nur`
if (!fs.existsSync(PATCH_LOCK)) {
  sh.exec('patch -p0 -i tools/cli-patches/webpack-enable-sourcemap.patch');
  sh.touch(PATCH_LOCK);
}

tools/cli-patches/webpack-enable-sourcemap.patch

--- node_modules/@angular/cli/models/webpack-configs/common.js 2018-02-08 09:10:11.000000000 +0800
+++ node_modules/@angular/cli/models/webpack-configs/common.js 2018-02-20 20:36:43.000000000 +0800
@@ -158,6 +158,7 @@
     }
     catch (e) { }
     return {
+        devtool: buildOptions.sourcemaps ? 'source-map' : false,
         resolve: {
             extensions: ['.ts', '.js'],
             modules: ['node_modules', nodeModules],

package.json

...
 "scripts": {
   "postinstall": "node tools/cli-patches/patch.js"
 }
...

So how do we use this? When is this going to be added to the actual CLI code?

patch doesn't work in 1.7.0. Trying to work on styling is a nightmare without sourcemaps, please fix!

I've never managed to make SCSS sourcemaps make work with any version of angular-cli!
v1.3.2 no sourcemaps, v1.6.0 no sourcemaps, now a clean project generated with v1.7.2 with nothing changed but a color for the header in the example and launched the project with ng serve -sm -ec or ng serve --sourcemap --extractCss and still no sourcemaps.

Any good pointers are appreciated. Thanks!

@avril-verhaeghen Developers recently added sourcemaps for component styles, which I believe is what broke global sourcemaps. Are you using global or component SCSS? I don't remember last version of angular-cli I was using before the maps broke (1.6.something I believe) but my build command is ng build --dev -ec --watch. Have you had any luck with non-served builds? You can also try verifying that your global cli version matches your local project, as well as do a global install of latest node-sass package -- though really don't think that should matter.

I use ng serve -sm -ec and it does not work for global styles. I don't use component styles.

@smlombardi @anthonyartese and if you import you vendor styles via the cli that too will not be mapped.

@michael-letcher I don't care about the vendor styles, but my main scss file, designsystem.scss is not getting mapped:

      "styles": [
        "../node_modules/prismjs/themes/prism.css",
        "../node_modules/@ngx-loading-bar/core/loading-bar.css",
        "../node_modules/ng2-toastr/bundles/ng2-toastr.min.css",
        "sass/designsystem/designsystem.scss",
        "styles.scss"
      ],

FWIW, it's not working for scss files imported into the styles.scss file either. Our styles.scss has an import of
@import 'documentation/documentation';

Yet, all of the classes from that css file, when inspected in dev tools, are all showing styles_bundle.css instead of their respective scss files.

+1, sourcemaps are not working for me. I'm importing pretty much all my scss files into /assets/scss/styles.scss (all of them being in sub folders following sass best practices 7:1 style guides) and none of them is accessible from the dev tools, they all get bundled up

Doesn't seem like this bug is going to be fixed anytime soon. My work around at the moment is to build the bundle using global install of node-sass:

node-sass ./src/styles/styles.scss --include-path ./src/styles --source-map-root file://{$pwd} --source-map-embed true --source-comments --source-map-contents ./dist/styles.bundle.css

This can likely be modified with a watch.

+1, no more source maps with @angular/cli: 1.7.1

v1.7.3 still no change. 👎

If this issue is not soon resolved, I will be incorporating a separate parallel CSS build process managed via gulp.

@adamfoley Any good ideas how to integrate that? I was also thinking of maybe using CodeKit for SCSS build, but not sure how to get the css file into the bundle.

@smlombardi I ended up going with gulp for now because I am working on styling and needed something that would also work for deploy. My config may be oversimplified, but it works. I am using font-awesome 4.7, bootstrap 4 and a single entry point for global SCSS. I added the font-awesome fonts as assets in .angular-cli.json so they get copied, a style sheet reference to project's index.html and emptied the styles array. In my styles/styles.scss file I set _$fa-css-prefix_, _$fa-font-path_ vars appropriately, then import font-awesome and bootstrap .SCSS from relative node_modules paths.

I have gulp calling ng cli commands defined in package.json. NOTE: May run into issues without _--delete-output-path=false_ on ng build command

added to index.html head:

<link href="styles.css" rel="stylesheet">

relevant styles.scss:

$fa-css-prefix: fa;
$fa-font-path: "assets/fonts";

@import "../../node_modules/font-awesome/scss/font-awesome";
@import "../../node_modules/bootstrap/scss/bootstrap";
@import "../../node_modules/bootstrap/scss/bootstrap-grid";

// .. other imports and custom SCSS

relevant package.json _scripts_:

"ngbuild": "ng build --prod -oh=none --delete-output-path=false",
"ngbuilddevw": "ng build --dev --watch --delete-output-path=false",

gulp dependencies:

"cssnano": "^3.10.0",
"gulp": "3.9.1",
"gulp-postcss": "7.0.1",
"gulp-rename": "1.2.2",
"gulp-sass": "3.2.0",
"gulp-sourcemaps": "2.6.4"

gulpfile.js:

const fs = require('fs');
const nodeSpawn = require('child_process').spawn;
const gulp = require('gulp');

const plugins = {
    sourcemaps: require('gulp-sourcemaps'),
    sass: require('gulp-sass'),
    postcss: require('gulp-postcss')
}
const cssnano = require('cssnano');

var STYLES_SRC = './src/styles/';
var STYLES_ENTRY = './src/styles/styles.scss';
var STYLES_DEST = './dist/';

var processors = [
    cssnano({
        discardComments: { removeAll: true },
        discardUnused: false, // unsafe, see http://goo.gl/RtrzwF
        zindex: false, // unsafe, see http://goo.gl/vZ4gbQ
        reduceIdents: false // unsafe, see http://goo.gl/tNOPv0
    })
];

var isProd = false;

// execute process
function spawn(command, args, cb) {
    var proc = nodeSpawn(command, args, {
        stdio: 'inherit',
        detached: false,
        env: process.env, shell: true
    });
    proc.on('error', function (err) { console.error(err) });
    if (cb != null) {
        proc.on('close', function (code, signal) { cb(code); });
    }
    return proc;
}

// watch styles task
gulp.task('watch::styles', ['build.styles'], function (done) {
    gulp.watch(STYLES_SRC + '**/*.scss', ['build.styles']);
});

// Build styles task
gulp.task('build.styles', function () {
    var src = 
        [STYLES_ENTRY];

    return isProd ?
        gulp.src(src)
            .pipe(plugins.sass({ includePaths: ['./node_modules/'] }).on('error', plugins.sass.logError))
            .pipe(plugins.postcss(processors))
            .pipe(gulp.dest(STYLES_DEST))
        : gulp.src(src)
            .pipe(plugins.sourcemaps.init())
            .pipe(plugins.sass({ includePaths: ['./node_modules/'] }).on('error', plugins.sass.logError))
            .pipe(plugins.sourcemaps.write(''))
            .pipe(gulp.dest(STYLES_DEST));
});

// task to build and watch dev
gulp.task('build.devw', function (done) {
    spawn('npm', ['run ngbuilddevw'], done);
    gulp.start('watch::styles');
});

// task to build prod
gulp.task('build.prod', function () {
        isProd = true;
    spawn('npm', ['run ngbuild'], function (code) {
        gulp.start('build.styles');
    });
});

Hope this is of some help.

My2cents. @michael-letcher I have tested using CLI 1.7.0 and can confirm the work around is no longer working. It was strange as the Webpack API related to the sourcemap fix did not change as far as I am concerned.

Did a little more digging & comparing the webpack config file, found that the new CLI is using Webpack plugin "raw-loader" which does not yet support sourcemap (somehow the ticket has been closed but I am not sure if the sourcemap has been implemented). See the link below:
https://github.com/webpack-contrib/raw-loader/pull/8

As for reference, there is a difference block of code in "webpack-config/style.js" file, the commonLoaders variable:

  • CLI 1.7.0 line 180: "raw-loader" is used
  • CLI 1.6.6 line 170: "css-loader" (and "postcss-loader") is used

"raw-loader" could be the issue here.

downgraded to 1.6.6 and applied fix by @CharltonC - source maps work as expected. my steps:

  • update global angular:
[sudo] npm uninstall -g @angular/cli 
npm cache clean 
[sudo] npm install -g @angular/cli
  • npm cache clear --force
  • npm cache verify
  • npm i @angular/[email protected] or use exact version in package.json "@angular/cli": "1.6.6", and do npm i
  • go to node_modules@angular\cli\models\webpack-configs\common.js:162
...
    catch (e) { }
    return {
        devtool: 'source-map',        // add this line
        resolve: {
            extensions: ['.ts', '.js'],
             ...
  • done

Had some spare time to test it out. As suspected, it was caused by "raw-loader" the plugin. I tried enabling the sourcemap with the option for "raw-loader" plugin like follows (approx. line 180) but unfortunately didn't work.

const commonLoaders = [
        { 
               loader: 'raw-loader',
               // option added here but didn't work
               options: {
                  sourceMap: cssSourceMap,
                  import: false,
            }                
        },
    ];

Perhaps the good news is that it is not a super verbose work around. It has turned into a verbose work around. It seems that "raw-loader" is only used for Html beside the "styles.js" file. Not sure what it may break though. Please do check.

Solution

  1. requires the devtool: 'source-map' in the "common.js" file as per previous discussion
  2. requires "css-loader" & "exports-loader" plugin to be installed as dependency in CLI
    a) in terminal, under your project folder, navigate to "node_modules/@angular/cli"
    b) install the plugin as dependency: npm install --save css-loader exports-loader
  3. in the file "node_modules@angular\cli\models\webpack-configs\styles.js" file, make a few changes:
    a) swap out the variable commonLoaders (approx. line 180) with css-loader one, for example:
    /*     const commonLoaders = [
        { loader: 'raw-loader' },
    ]; */
   // new code looks something like this
    const commonLoaders = [
        {
            loader: 'css-loader',
            options: {
                sourceMap: cssSourceMap,
                import: false,
            }
        }
    ];
   ...

b) Right underneath the commonLoaders, add the 'exports-loader?module.exports.toString()', above the ...commonLoaders. This is the same as CLI 1.6.6 and eliminates the error "compiler.js:2520 Uncaught Error: Expected 'styles' to be an array of strings." in the devtool console

    ...
    // load component css as raw strings
    const rules = baseRules.map(({ test, use }) => ({
        exclude: globalStylePaths, test, use: [
            'exports-loader?module.exports.toString()',           // <-- add this line
            ...commonLoaders,
            {
                loader: 'postcss-loader',
                ...

Test Context:

  • angular-cli version 1.7.0
  • node v6.9.4
  • Scss

Tested with the following Commands in terminal (also works with Sass @import):

ng serve           // no sourcemap
ng serve -sm -ec   // has sourcemap
ng serve --sourcemap --extract-css  // has sourcemap   
ng serve --sourcemap --extractCss   // has sourcemap   

@CharltonC Doesn't work for me. Throws a mess of errors, beginning with a missing font (which did not happen before the fix).

@smlombardi ~~
~~Yes you are right. Sorry I missed the error in the console saying "compiler.js:2520 Uncaught Error: Expected 'styles' to be an array of strings.". which cause the page not displaying correctly even though the sourcemaps is working. Will need to take another look.

@smlombardi edited the solution, turned out I missed to specify another plugin when playing with the solution. I can confirm it is working now in my development environment without the console error and UI is showing correctly. Can you verify again to see if it works?

Nope. Same initial error, with a bunch of other errors. They are all font-related.


ERROR in ./src/sass/designsystem/designsystem.scss
Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve './PrecisionSans_W_Bd.61449ec099a8a01e77f9.woff' in '/Users/st016lo/github/ng-designsystem/client/src/sass/designsystem'
    at factoryCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/Compilation.js:276:40)
    at factory (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:237:20)
    at resolver (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:60:20)
    at asyncLib.parallel (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:127:20)
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:3874:9
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:473:16
    at iteratorCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:1048:13)
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:958:16
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:3871:13
    at resolvers.normal.resolve (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:119:22)
    at onError (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:65:10)
    at loggingCallbackWrapper (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at runAfter (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
    at innerCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
    at loggingCallbackWrapper (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/st016lo/github/ng-designsystem/client/node_modules/tapable/lib/Tapable.js:252:11)
ERROR in ./node_modules/font-awesome/css/font-awesome.min.css
Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve './fontawesome-webfont.674f50d287a8c48dc19b.eot' in '/Users/st016lo/github/ng-designsystem/client/node_modules/font-awesome/css'
    at factoryCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/Compilation.js:276:40)
    at factory (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:237:20)
    at resolver (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:60:20)
    at asyncLib.parallel (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:127:20)
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:3874:9
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:473:16
    at iteratorCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:1048:13)
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:958:16
    at /Users/st016lo/github/ng-designsystem/client/node_modules/async/dist/async.js:3871:13
    at resolvers.normal.resolve (/Users/st016lo/github/ng-designsystem/client/node_modules/webpack/lib/NormalModuleFactory.js:119:22)
    at onError (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:65:10)
    at loggingCallbackWrapper (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at runAfter (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
    at innerCallback (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
    at loggingCallbackWrapper (/Users/st016lo/github/ng-designsystem/client/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/st016lo/github/ng-designsystem/client/node_modules/tapable/lib/Tapable.js:252:11)
ERROR in ./src/sass/designsystem/designsystem.scss

and so one for every font.

This gets to a point where it just takes too much effort or work around to solve a fundamental issue. There are too many unknowns as in what we need to test against the solution so that other functionalities don't break because the work around involves changes in so many areas. I think it would best to leave this to original author as in why there was a major change in the implementation from v1.7.0 onwards.

I can share some observations for reference purpose only. Apart from the changes I mentioned, if you do either of the following, the font error mentioned by @smlombardi disappears.

  • If you replace the node_modules\@angular\cli\models\webpack-configs\style.js file from CLI v1.6.6 to CLI v1.70 it will work. (requires an extra npm dependency called cssnano for the CLI)
  • If you comment out the PostcssCliResources in the postcssPluginCreator constant in the node_modules\@angular\cli\models\webpack-configs\style.js file, like following (It is using a node_modules\@angular\cli\plugins\postcss-cli-resources.js file which was not in v1.6.6 before):
    ```Javascript
    ...
    { url: 'rebase' },
    ]),
    // PostcssCliResources({
    // ...
    // }) ,
    autoprefixer({ grid: true }),
    ];
    ````

Hope this helps. For now I myself am just going to stick with CLI v1.6.6

One just wonders when the team is planning to actually fix this critical piece of tooling.

version 1.7.3 does't work, even patched with devtool: 'source-map', anyone know why

I don't think the sourcemap is working for the Command ng build -sm -ec in both CLI v1.6.6 and v1.7.0 although there is a test/spec file in the CLI source code that says so.

In the CLI source code, I only managed to find only one test that is relevant to scss style and sourcemap in tests/e2e/build/styles/import.ts file (around line 48). It looks like this:

...
        .then(() => ng('build', '--extract-css', '--sourcemap'))    // <---- simulate cli cmd
        // verify global styles
        .then(() => expectFileToMatch('dist/styles.bundle.css',
          /body\s*{\s*background-color: #00f;\s*}/))
        .then(() => expectFileToMatch('dist/styles.bundle.css',
          /p\s*{\s*background-color: #f00;\s*}/))
        // verify global styles sourcemap
        .then(() => expectToFail(() =>
          expectFileToMatch('dist/styles.bundle.css', '"mappings":""')))     // <---- this test
...

Now an external scss sourcemap file content example would look something like this:

{"version":3,"sources":["main.scss"],"names":[],"mappings":"AACA;EACI,mBAAmB,EACtB","file":"main.css","sourcesContent":["// @import '_common/_reset.2.0.min.scss';\r\nbody {\r\n    font-family: Arial;\r\n}"]}

The mappings property in an external source map file should not be empty if there is the scss file has any content at all (compared to the spec/test in CLI source code above). In addition, it would also outline your source scss filename however the actual generated external source map file (when you run the command ng build -sm -ec in CLI v1.6.6 & v1.7.0) just contains ".css" filename (i.e. correspond to the output file main.css in the source map example above). Is the spec/test testing the source map correctly? Would appreciate if anyone else can share their findings.

version 1.7.4 still not work, even try patched with devtool: 'source-map', Plz show me how to fix this issue.

Has anyone tested if scss sourcemaps work in version 6.0 (to be released with angular 6.0)? For angular v5 I just stayed on v1.6.x and used CharltonC fix provided here. Note that fix does not work with 1.7.x versions of cli.

@hiepnguyen93 seems the only stable thing you can do is downgrading to 1.6.6, I provided my steps in the post above

Thanks for your help, I was downgrade angular cli and it run normaly. :D

any workaround? I am unable to use cli 1.6.6

works for me using version 6.0!!

solution:

  1. modify angular.json to add __--extract-css, in 6.0 this argument is removed from ng serve__
 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
           ---
          },
          "configurations": {
            "production": {
              ---
            },
            "serve": {
              "extractCss": true,
               ---
            }
          }
        },

hen change _serve->options->browserTarget->project-name:build_ to _project-name:build:serve_

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "open": true,
            "browserTarget": "<project-name>:build:serve"
          },
          "configurations": {
            "production": {
              ---
            }
          }
        }
  1. run
    ng serve --source-map
    image

@metasong Thanks! That works for me. At least for "global" sass files. Component sass styles still don't get source mapped, but I don't use those anyways. Something to consider for others though.

For others' reference, source maps for sass files were broken in the CLI way back in version 1.5.0. It's getting old now, but using cli version 1.4.x and older will work as expected when running:

ng serve -sm -ec

https://github.com/angular/angular-cli/issues/8314

@CharltonC Thanks, your solution worked for me for angular cli 1.7.4. It is now showing the scss sourcemaps.
#issuecomment-373430066

@frensuren , can you share the exact steps you did? having a hard time following which of the solution will work for 1.7.4

@rukshandangalla Could this ticket be closed now that v6 issue has been fixed?

@rukshandangalla For me, component sass styles still don't get source mapped (v6).

@icenold
Installed css-loader and exports-loader dependencies for @angular/cli
i) navigate to "node_modules/@angular/cli"
ii) do: npm install --save css-loader exports-loader
iii) Modify the file "node_modules@angular\cli\models\webpack-configs\styles.js" contents, mine was in line 180
Replace

     const commonLoaders = [
        { loader: 'raw-loader' },
    ]; 

with this

const commonLoaders = [
        {
            loader: 'css-loader',
            options: {
                sourceMap: cssSourceMap,
                import: false,
            }
        }
    ];

Also
Replace

 // load component css as raw strings
    const rules = baseRules.map(({ test, use }) => ({
        exclude: globalStylePaths, test, use: [
            ...commonLoaders,
            {
                loader: 'postcss-loader',
                options: {
                    ident: 'embedded',
                    plugins: postcssPluginCreator,
                    sourceMap: cssSourceMap
                }
            },
            ...use
        ]
    }));

With

// load component css as raw strings
    const rules = baseRules.map(({ test, use }) => ({
        exclude: globalStylePaths, test, use: [
                'exports-loader?module.exports.toString()',
                ...commonLoaders,
            {
                loader: 'postcss-loader',
                options: {
                    ident: 'embedded',
                    plugins: postcssPluginCreator,
                    sourceMap: cssSourceMap
                }
            },
            ...use
        ]
    }));

This worked for me

Sourcemapping for General (Non-component level) SCSS Compilation

@metasong's solution works for ANGULAR 6

  1. modify angular.json to add --extract-css, in 6.0 this argument is removed from ng serve
 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
           ---
          },
          "configurations": {
            "production": {
              ---
            },
            "serve": {
              "extractCss": true,
               ---
            }
          }
        },
  1. Then change serve->options->browserTarget->project-name:build to project-name:build:serve
"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "open": true,
            "browserTarget": "<project-name>:build:serve"
          },
          "configurations": {
            "production": {
              ---
            }
          }
        }
  1. run ng serve --source-map

image

Sourcemapping for Component-level SCSS Files

Can you confirm, @metasong, @frensuren, @CharltonC, @rukshandangalla, @michael-letcher?

Suprisingly, the following solution works without any configuring of Angular 6's angular.json file.

Simply add /*# sourceURL=your-comp-style.component.scss */ to the bottom of your component-level .scss file.

Code

screen shot 2018-06-06 at 3 30 06 pm

Run

ng serve --source-map

Result in Chrome

screen shot 2018-06-06 at 3 37 02 pm

@cedriccjmusic

Source mapping for Component-level

Can confirm that adding /*# sourceURL=navbar.component.less */ worked for me.
Note this is using LESS

Source mapping for General (Non-component level)

I don't need to do this, LESS seems to work by just using --source-map

This is causing an error for me:

Schema validation failed with the following errors:
  Data path "" should NOT have additional properties(extractsCss).

The sourceURL= solution helps at least tell you the file, but still is far from ideal. It references generated css, so line numbers do not match up and any imported styles will show as belonging to the importing file.

@daddyschmack you have a typo, it should be extractCss and not extractsCss, although I was trying this method with a new angular project and its not working with the last couple cli versions.

I found the source of the issue within the @angular-devkit/build-angular package.

You can temporarily fix this yourself editing changing the sourcemap option for both instances of postcss-loader in the following file
./node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/styles.js
change

sourceMap: cssSourceMap

to

sourceMap: cssSourceMap ? 'inline' : false
    const rules = baseRules.map(({ test, use }) => ({
        exclude: globalStylePaths, test, use: [
            { loader: 'raw-loader' },
            {
                loader: 'postcss-loader',
                options: {
                    ident: 'embedded',
                    plugins: postcssPluginCreator,
                    sourceMap: cssSourceMap ? 'inline' : false
                }

I'll file an issue with the @angular-devkit/build-angular repository.
edit: ah that package is in this repo, ha. I submitted a pull request with the fix.

@cedriccjmusic thanks for the example!

Sadly isn't working for me with Angular cli 6.1

I get the following result:
screen shot 2018-08-09 at 13 16 22

Versions

Angular CLI: 6.1.2
Node: 8.11.1
OS: darwin x64
Angular: 6.1.1
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, platform-server
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.7.2
@angular-devkit/build-angular     0.7.2
@angular-devkit/build-optimizer   0.7.2
@angular-devkit/build-webpack     0.7.2
@angular-devkit/core              0.7.2
@angular-devkit/schematics        0.7.2
@angular/cli                      6.1.2
@angular/compiler-cli             6.1.2
@angular/language-service         6.1.2
@ngtools/webpack                  6.1.2
@schematics/angular               0.7.2
@schematics/update                0.7.2
rxjs                              6.2.2
typescript                        2.9.2
webpack                           4.9.2

Config

{
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        ....
        "stylePreprocessorOptions": {
          "includePaths": [
            "styles/core-scss"
          ]
        },
        "assets": [
          ....
        ],
        "styles": [
          "apps/essent/src/core.scss"
        ],
        "scripts": []
      },
      "configurations": {
        "production": {
          ....
        },
        "css": {
          "sourceMap": true,
          "extractCss": true
        }
      }
    },
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "essent:build",
        "port": 4200
      },
      "configurations": {
        "production": {
          "browserTarget": "essent:build:production"
        },
        "css": {
          "browserTarget": "essent:build:css"
        }
      }
    }
  }

Commands

Getting the same result with build & serve

yarn ng build essent --source-map --extract-css
yarn ng serve essent --proxy-config proxy.conf.js --configuration css --source-map

@ajspera this won't fix angular-cli 1.7.4, am I right? only new 6.x.x?

@lazysergey Right. You might want to try #issuecomment-392316835 who had a hack working for 1.7.4. I would recommend getting up to 6, though. The next minor patch should have the fix in.

@ajspera were you able to get smaps to work? Is there somewhere I could read up on how to get them to work properly? I've never actually seen them work in Angular.

@BenRacicot Hmm, they said it would be in this past patch release but I don't see the commit in branch 6.2.x. It's on master, so it's in the maintainers' hands at this point. If you are desperate, you can make the changes from the commit mentioned above in your installation's source. It's only 2 lines.

Awesome thanks for replying.

Still sourceMap / extractCSS is not working for component specific styles

image

"@angular-devkit/build-angular": "^0.6.8",
"@angular/cli": "^6.0.8",

@metasong's solution is working for Angular 6+ projects

Any update on this? @metasong's solution doesn't work on component style.
Pls support LESS source map!!! This is suck a basic feature.

@clydin @hansl guys, I believe this is not fixed in version 7.1.0, why close this issue?

@camsong It works fine for me in version 7.0.4
This issue only about SCSS source maps.

It's working for me on version 7.0.3.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings