Working SCSS Sourcemaps with Angular 6

If you are an Angular developer, you’ve probably noticed that since Angular 2+ they break with almost every release. After wasting many hours in futile attempts to fix them and going through numerous report on Angular GitHub page I finally got to a setup that works.

Fixing dependencies (vendor) sourcemaps

  1. Open angular.json and find targets->build->configurations
  2. Add a new configuration after production. Name it serve.
    "configurations": {
      "production": {
        ...
      }
      "serve": {
        "extractCss": true
      }
    
  3. Change serve task to use the new config by changing targets->serve->options
    "options": {
      "browserTarget": "PROJECT_NAME:build:serve"
    
  4. Open package.json and update start scripts
    "scripts: {
        ...
        "start": "ng serve --source-map --vendor-source-map --ssl",
    }
    
  5. Run your project with npm start. Inspect your markup. You’ll see dependencies SCSS using the source maps and showing correct paths.


This will solve vendor sourcemaps issues, however you’ll see that your components sourcemaps aren’t working like before.

Fixing components sourcemaps

Components css is inlined on compile. The solution is to force inline sourcemaps as well. In order to do that we’ll need to match @angular-devkit

  1. Install shelljs as a dev dependency
    npm install shelljs --save-dev
    

    This will allow us to run shell scripts from nodejs.

  2. Create 2 files under tools/cli-patches at project root.

    • patch.js

    • enable-sourcemaps.patch

  3. Add a postinstall script in package.json that will patch @angular-devkit and force inline sourcemaps for components on serve. Your scripts will now look like this:
    "scripts": {
      "ng": "ng",
      "start": "ng serve --source-map --vendor-source-map --ssl",
      "build": "ng build",
      "test": "ng test",
      "lint": "ng lint",
      "e2e": "ng e2e",
      "postinstall": "node tools/cli-patches/patch.js"
    },
    
    • Do npm install or npm run postinstall to force the patching.
    • Always use npm start instead of ~~ng serve~~ to start your project. Once you run the server you’ll see correct files and code paths on components.
WARNING:

The patch might break with any future version of @angular-devkit. If this happens you’ll need to generate another patch file using git diff.

Sources:
Angular GitHub issues discussions
Angular CLI sourcemaps issue

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.