ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

bug: source maps are not loaded when debugging with chrome dev tools on device

Open KevinKelchen opened this issue 5 years ago • 44 comments

Bug Report

Ionic Info

Ionic:

   ionic (Ionic CLI)             : 4.4.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.0.0-beta.16
   @angular-devkit/build-angular : 0.10.6
   @angular-devkit/schematics    : 7.0.6
   @angular/cli                  : 7.0.6
   @ionic/angular-toolkit        : 1.2.0

Cordova:

   cordova (Cordova CLI) : 8.1.2 ([email protected])
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.2.5, (and 4 other plugins)

System:

   Android SDK Tools : 26.1.1 (/Users/kelchen/Library/Android/sdk)
   ios-deploy        : 2.0.0
   ios-sim           : 7.0.0
   NodeJS            : v10.13.0 (/usr/local/bin/node)
   npm               : 6.4.1
   OS                : macOS
   Xcode             : Xcode 10.1 Build version 10B61

Describe the Bug TypeScript source maps are not present when debugging on an Android device/emulator.

Steps to Reproduce Steps to reproduce the behavior:

  1. Start a new project with ionic start sourcemaps blank --type=angular.
  2. Path into the project directory and run ionic cordova prepare android. Say Y to the prompt to install the Android platform.
  3. Run ionic cordova prepare android again. It will download/install the Cordova plugins that are part of the template.
  4. Run ionic cordova run android. This will build the app and deploy it to an Android emulator. You could also choose to deploy to a device by connecting a device configured for debugging and passing the --device flag to this command.
  5. After you get the app deployed and running on the emulator, in a Google Chrome tab go to chrome://inspect/#devices and inspect the Ionic app.
  6. In the Chrome DevTools under Sources use Cmd + P to search for the source file home.page.ts. It will not be found.

image

Related Code If you are able to illustrate the bug with an example, please provide a sample application via an online code collaborator such as StackBlitz, or GitHub.

Expected Behavior I expected the TypeScript source files to be present and debuggable with breakpoints in the Chrome DevTools.

Additional Context This is the same issue as #15152 which has since been closed and locked. While the OP of that issue decided to use Ionic DevApp as a workaround, our application uses a number of additional and different Cordova plugins that make using DevApp unsuitable. I would expect the browser dev tools to work like they have previously in Ionic 3 and like they currently do with iOS.

KevinKelchen avatar Nov 26 '18 18:11 KevinKelchen

I have this problem too. I am only able to debug by putting in console.log statements. Please fix this!

sarahmluo avatar Nov 29 '18 04:11 sarahmluo

@manucorporat it here any way to add source maps to Android, too? I can confirm this issue

paulstelzer avatar Dec 03 '18 17:12 paulstelzer

Same problem. This occurs with either of Capacitor or Cordova wrapper.

Tried adding sourcemaps = 'inline-source-map'; to C:\dev\ionic\sqlite-test\node_modules\@angular-devkit\build-angular\src\angular-cli-files\models\webpack-configs\browser.js as suggested here, but did not help.

Debugging the TypeScript when running on an emulator (or device) is still very essential when the app replies on plugin(s)

pjc2007 avatar Dec 26 '18 09:12 pjc2007

Actually, I did get it working by following the above, but I needed to add the 'inline-source-map into the else block, ie line 28 in browser.js. I then noticed the source maps where now in the js files, and I could then find the TypeScript files under webpack://_/src within the chrome dev tools.

Would still be a lot better if we did not have to edit the Angular build file, as this we could forget and lose this if node_modules refreshed.

pjc2007 avatar Dec 26 '18 10:12 pjc2007

Thanks for your investigation! Can you maybe open a feature request at https://github.com/ionic-team/ionic-cli/issues and link this issue here?

paulstelzer avatar Dec 26 '18 12:12 paulstelzer

Tried adding sourcemaps = 'inline-source-map'; to C:\dev\ionic\sqlite-test\node_modules\@angular-devkit\build-angular\src\angular-cli-files\models\webpack-configs\browser.js as suggested here, but did not help.

Are you sure that you run the build with --eval-source-map param (as suggested in my original post)? What is @angular/cli version? 7.0.0?

ryaa avatar Jan 30 '19 04:01 ryaa

Would still be a lot better if we did not have to edit the Angular build file, as this we could forget and lose this if node_modules refreshed.

There are some options to enable this without editing angular sources - see https://github.com/angular/angular-cli/issues/13543#issuecomment-458663189 I think i will try to use custom tools to extend the Angular CLI build behaviour, for example using https://github.com/manfredsteyer/ngx-build-plus to see how it goes

ryaa avatar Jan 30 '19 04:01 ryaa

To whom it may concern, here is the approach I implemented to enable debugging with source maps support on Android devices

  • install ngx-build-plus by running npx ng add ngx-build-plus
    This will install the required npm package and update angular.json as required For more details please see https://github.com/manfredsteyer/ngx-build-plus
  • create new file build-customization-plugin.js in the project root directory and add the below content in this file
var merge = require('webpack-merge');

exports.default = {
    config: function (cfg) {
        const strategy = merge.strategy({
            'devtool': 'replace',
        });

        return strategy(cfg, {
            devtool: 'inline-source-map'
        });
    }
}
  • run ng build --eval-source-map --plugin ~build-customization-plugin.js from the root directory to build the project with source maps to debug on Android devices

This is a better approach then changing angular/cli source :)

ryaa avatar Feb 06 '19 06:02 ryaa

I have the same issue. @IonicProSupport I need to debug android devices and for now I am not able, I hope you find a fix soon

alexcarrasco93 avatar Feb 20 '19 12:02 alexcarrasco93

I have the same issue. @IonicProSupport I need to debug android devices and for now I am not able, I hope you find a fix soon

Yes. It is described above and works fine for me.

ryaa avatar Feb 20 '19 12:02 ryaa

@ryaa I tried your solution but didn't work for me.

Option "evalSourceMap" is deprecated.
Unknown option: '--plugin'
Unknown option: '~build-customization-plugin.js'

I hope the @IonicProSupport team find an official solution

alexcarrasco93 avatar Feb 20 '19 12:02 alexcarrasco93

Any updates on this? It is very annoying

senioroman4uk avatar Feb 23 '19 22:02 senioroman4uk

I've done a script to work around this while we wait for the fix, just execute it with node:

const fs = require('fs');
const path = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';

let file = fs.readFileSync(path, { encoding: 'utf8' });
file = file.replace('source-map', 'inline-source-map');
fs.writeFileSync(path, file, 'utf8');

ElianCordoba avatar Apr 16 '19 09:04 ElianCordoba

@ElianCordoba which version of @angular-devkit/build-angular you are using? It doesn't work for me with v0.13.7. 'source-map' doesn't exists anymore in browser.js :(

amb-jarek avatar Apr 19 '19 13:04 amb-jarek

@amb-jarek I'm using v0.13.6

ElianCordoba avatar Apr 19 '19 15:04 ElianCordoba

Same issue here when using ionic cordova run --device android --livereload --ssl

Ionic:

   ionic (Ionic CLI)             : 4.12.0 (/home/esoares/.npm-global/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.3.1
   @angular-devkit/build-angular : 0.12.4
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.2.4
   @ionic/angular-toolkit        : 1.3.0

Cordova:

   cordova (Cordova CLI) : 9.0.0 ([email protected])
   Cordova Platforms     : android 8.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 6 other plugins)

System:

   Android SDK Tools : 26.1.1 (/home/esoares/Android/Sdk)
   NodeJS            : v8.16.0 (/usr/bin/node)
   npm               : 6.4.1
   OS                : Linux 4.15

iget-master avatar Apr 28 '19 21:04 iget-master

To whom it may concern, here is the approach I implemented to enable debugging with source maps support on Android devices

  • install ngx-build-plus by running npx ng add ngx-build-plus This will install the required npm package and update angular.json as required For more details please see https://github.com/manfredsteyer/ngx-build-plus
  • create new file build-customization-plugin.js in the project root directory and add the below content in this file
var merge = require('webpack-merge');

exports.default = {
    config: function (cfg) {
        const strategy = merge.strategy({
            'devtool': 'replace',
        });

        return strategy(cfg, {
            devtool: 'inline-source-map'
        });
    }
}
  • run ng build --eval-source-map --plugin ~build-customization-plugin.js from the root directory to build the project with source maps to debug on Android devices

This is a better approach then changing angular/cli source :)

在angular.json 添加 evalSourceMap ,plugin 配置 在 projects->app>root>architect->build>options 下添加 "evalSourceMap":true, "plugin":"~build-customization-plugin.js",

konghao8013 avatar May 23 '19 12:05 konghao8013

Having this too, just bumping the issue...

$ ionic info

Ionic:

   Ionic CLI                     : 5.0.3 (C:\Users\maxim\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.5.0
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   Cordova CLI       : 9.0.0 ([email protected])
   Cordova Platforms : android 8.0.0
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 18 other plugins)

Utility:

   cordova-res : 0.3.0
   native-run  : 0.2.5

System:

   Android SDK Tools : 26.1.1 (C:/Users/maxim/AppData/Local/Android/Sdk)
   NodeJS            : v10.15.3 (C:\Program Files\nodejs\node.exe)
   npm               : 6.9.0
   OS                : Windows 10

Added to my package.json:

  "config": {
    "ionic_bundler": "webpack",
    "ionic_source_map_type": "#inline-source-map"
  },

Running ionic cordova run android --livereload --ssl --source-map, I can't see any source maps, can't access them on the server and they are not referenced in the JS files.

Running ionic cordova run android --source-map, I can see source maps created, they are copied to the phone and they are references in the JS files. But I still can't see any webpack:// folder in the Sources tab of Chrome Dev Tools.

maxpaj avatar Jun 20 '19 18:06 maxpaj

I've successfully got source maps on my device with following workaround:

add following to your ionic.config.json:

{
  [...],

  "hooks": {
    "build:after": "./attach-source-maps.js"
  }
}

Then create attach-source-maps.js in the root of your project with following content:

let fs = require('fs');
let path = require('path');

const TARGET_DIR = 'www';

module.exports = function (ctx) {
    console.log('=====================');
    console.log('attaching source maps');
    console.log('=====================');

    let files = fs.readdirSync(TARGET_DIR);

    files.forEach(file => {
        let mapFile = path.join(TARGET_DIR, file + '.map');
        let targetFile = path.join(TARGET_DIR, file);
        if (path.extname(file) === '.js' && fs.existsSync(mapFile)) {
            let bufMap = fs.readFileSync(mapFile).toString('base64');
            let bufFile = fs.readFileSync(targetFile, "utf8");
            let result = bufFile.replace('sourceMappingURL=' + file + '.map', 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + bufMap);
            fs.writeFileSync(targetFile, result);
        }
    });
};

At the end adjust script to your needs - eg disable it for prod build

amb-jarek avatar Jun 25 '19 11:06 amb-jarek

@amb-jarek can you give some more information? What is your ionic info and what command line arguments do you use?

maxpaj avatar Jun 25 '19 11:06 maxpaj

@maxpaj

Ionic:

   ionic (Ionic CLI)             : 4.12.0 (/home/jarek/.nvm/versions/node/v8.9.4/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.4.0
   @angular-devkit/build-angular : 0.13.7
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.3.7
   @ionic/angular-toolkit        : 1.4.1

Cordova:

   cordova (Cordova CLI) : 7.1.0
   Cordova Platforms     : android 6.4.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 26 other plugins)

System:

   NodeJS : v8.9.4 (/home/jarek/.nvm/versions/node/v8.9.4/bin/node)
   npm    : 5.6.0
   OS     : Linux 4.4

provided hook is working for me when I execute:

ionic cordova build android

or

ionic cordova run android --device

amb-jarek avatar Jun 25 '19 11:06 amb-jarek

Thanks . @amb-jarek working now with your workaround.

bhavin9695 avatar Jul 02 '19 10:07 bhavin9695

I can confirm that the workaround seems to work for me as well. Does anyone at Ionic have any update on this, though? This is a pretty annoying issue for people using Ionic to have to deal with source-maps not working on Android.

ekrapfl avatar Oct 01 '19 18:10 ekrapfl

Fwiw, I did make one tweak for my own purposes. We wanted this to happen only for Android, and not for a release build, so I added this to the top of the function:

if (ctx.argv.includes('--release') || ctx.build.platform !== "android")
    return;

ekrapfl avatar Oct 02 '19 13:10 ekrapfl

Struggled with the same issues as described here but didn't want to use ngx-build plus, because the build times increased a lot. Just got it to work however using capacitors live reload tool, which additionally adds the advantage of live reloading on the device. When I use ionic cap run android -l --address=my.local.ip --source-map (where my.local.ip is the local ip of the pc running the build server) to deploy to the android device, the source maps are available to the debugger. I guess thats because they aren't loaded of the device anymore but rather from the development server. More on Capacitor live reloading here.

tva-TIS avatar Mar 11 '20 14:03 tva-TIS

Might be useful to mention that i'm using Ionic 5 and Angular 9 with Ivy.

tva-TIS avatar Mar 11 '20 14:03 tva-TIS

The problem persist with Ionic 5 and Last React

gine avatar May 19 '20 15:05 gine

I've successfully got source maps on my device with following workaround:

I use Ionic V5 and React here some modification at your workaround.

I suggest to create the scripts on the root project and to put the attach-source-maps.js here so you must modify ionic.config.json:

   "hooks":{
     "build:after": "./scripts/attach-source-maps.js"
   },

const TARGET_DIR = 'www';

Then the TARGET_DIR dir on the script must be modified as follow:

const TARGET_DIR = 'build/static/js';

Then you must add on your tsconfig.json file:

  "include": [
    "src", "scripts"
  ]

At the end adjust script to your needs - eg disable it for prod build

This still valid.

gine avatar May 19 '20 16:05 gine

https://github.com/ionic-team/ionic-framework/issues/16455#issuecomment-505397373 - This should be the accepted answer until the fix is provided by ionic team.

I have further enhanced @amb-jarek response to include SCSS sourcemaps as well, in case your angular app uses SASS like mine:

let fs = require('fs');
let path = require('path');

const TARGET_DIR = 'www';

module.exports = function (ctx) {
    console.warn('=====================');
    console.warn('WARNING: Sourcemaps have been manually added. Ensure this is disabled in production!');
    console.warn('=====================');

    let files = fs.readdirSync(TARGET_DIR);

    files.forEach(file => {
        let mapFile = path.join(TARGET_DIR, file + '.map');
        let targetFile = path.join(TARGET_DIR, file);
        if (path.extname(file) === '.js' && fs.existsSync(mapFile)
            || path.extname(file) === '.css' && fs.existsSync(mapFile)) {
            let bufMap = fs.readFileSync(mapFile).toString('base64');
            let bufFile = fs.readFileSync(targetFile, "utf8");
            let result = bufFile.replace('sourceMappingURL=' + file + '.map', 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + bufMap);
            fs.writeFileSync(targetFile, result);
        }
    });
};

Note: This fix increases your bundle size (apk) and should be manually disabled in production. Before taking a production build ensure the following hook scripts are removed from ionic.config.json file.

"hooks": {
    "build:after": "./attach-source-maps.js"
  }

evanmonfee avatar Jul 11 '20 11:07 evanmonfee

@amb-jarek Thank you for the hook, it works perfectly.

For those who want to apply the hook only for debugging on android device just add the following condition on the context :

if (!ctx.argv.includes("--device") || ctx.build.platform !== "android")
    return;

CodeTroopers avatar Aug 18 '20 17:08 CodeTroopers

Angular CLI will never allow devtools options for inline-source-maps. Search the Angular CLI issues. I cannot understand this decision. Anyway... The problem with the DevTools in Chromium (device inspect) is that the url of source maps refer to "localhost". The localhost of the device. But the DevTools does not know the url of the device. So it is trying to fetch from the localhost of the computer. So, what can we do?

  1. Finding a way to set the correct url of the device. Maybe a setting in Cordova? I don't know. But I think, even if the url contains the ip address of the device, it will not work. Because it's a local app. You cannot access app files through your network. Only if the app provides it using a server. Ideas are welcome. But I think that this possible solution will not work.

  2. Tell Angular CLI to use inline-source-maps. But the Angular CLI developer team decided against this option. So you have to use 3rd party libs to get access to the webpack.config.js. Or reject the Angular CLI and use Webpack and build by your own scripts. That is probably very time-consuming and painful.

  3. Use a node script to add the map-files as base64 string to the js-files. Build your own inline-source-map assignment. This "hack" has limitations. But it might generally work with apk bundles. I think this does not work with live reload.

Conclusion: Sadly the Angular CLI team will not provide a inline source map option. See issue Life would be a lot easier with this option. ... That is disappointing.

y0nd0 avatar Oct 06 '20 19:10 y0nd0

@y0nd0

  1. Finding a way to set the correct url of the device. Maybe a setting in Cordova? I don't know. But I think, even if the url contains the ip address of the device, it will not work. Because it's a local app. You cannot access app files through your network. Only if the app provides it using a server. Ideas are welcome. But I think that this possible solution will not work.

Serving the files from the computer is exatly what is happening with livereload as i mentioned here. You need to set the url to use by using the host flag (which has deprecated the address flag I described orginally). While using this I realized, that this run sets a server.url Parameter within the capacitor.config.json. Maybe this can be used without live-reload too.

tva-TIS avatar Oct 07 '20 05:10 tva-TIS

Is official Live Reload support planned? A full rebuild for every small change is the worst way to work.

I'm on Cordova + Angular 9 + Ionic stack, any kind of fast dev-work seems impossible.

https://github.com/ionic-team/ionic-app-scripts/issues/822 https://github.com/ionic-team/ionic-app-scripts/issues/1354

I hope this issue doesn't get closed without a fix like the previous threads.

AlphaJuliettOmega avatar Nov 06 '20 14:11 AlphaJuliettOmega

To whom it may concern, here is the approach I implemented to enable debugging with source maps support on Android devices

  • install ngx-build-plus by running npx ng add ngx-build-plus This will install the required npm package and update angular.json as required For more details please see https://github.com/manfredsteyer/ngx-build-plus
  • create new file build-customization-plugin.js in the project root directory and add the below content in this file
var merge = require('webpack-merge');

exports.default = {
    config: function (cfg) {
        const strategy = merge.strategy({
            'devtool': 'replace',
        });

        return strategy(cfg, {
            devtool: 'inline-source-map'
        });
    }
}
  • run ng build --eval-source-map --plugin ~build-customization-plugin.js from the root directory to build the project with source maps to debug on Android devices

This is a better approach then changing angular/cli source :)

The above does not work for the latest angular cli (@angular-devkit/* with version 0.1000.0 and above)

To enable this workaround again please update build-customization-plugin.js file in the project root directory to make it look as below

const merge = require('webpack-merge');
const webpack = require("webpack");

exports.default = {
    config: function (cfg) {

        // first, we replace devtool in the webpack used by the angular cli to have the value 'inline-source-map'
        const strategy = merge.strategy({
            'devtool': 'replace',
        });
        const result = strategy(cfg, {
            devtool: 'inline-source-map'
        });

        // then we find SourceMapDevToolPlugin and remove it
        // This is because we should never use both the devtool option and plugin together.
        // The devtool option adds the plugin internally so you would end up with the plugin applied twice.
        // See https://webpack.js.org/configuration/devtool/
        const index = result.plugins.findIndex((plugin) => {
            return plugin instanceof webpack.SourceMapDevToolPlugin;
        });
        result.plugins.splice(index, 1);

        return result;
    }
}

All the rest is the same

ryaa avatar Dec 29 '20 06:12 ryaa

I'm on Ionic 6, with angular 13 and I can't debug my project on android.... because there are no source-maps

Funny thing is: I can debug on iOS because safari's inspect does have the source

Franco-Alejandro avatar Mar 02 '22 15:03 Franco-Alejandro

I’m not sure if it’s changed recently, but using Capacitor with Live Reload will result in source maps working on Android (at least it does for us).

I know that doesn’t help if the app is using Cordova or there’s a desire to not use Live Reload though.

Hope that could help!

KevinKelchen avatar Mar 02 '22 17:03 KevinKelchen

I’m not sure if it’s changed recently, but using Capacitor with Live Reload will result in source maps working on Android (at least it does for us).

I know that doesn’t help if the app is using Cordova or there’s a desire to not use Live Reload though.

Hope that could help!

Works for me too. Regarding the "not wanting live reload" aspect: When I was using live reload, Capacitor just set the App-URL in capacitor.config.json to the host IP I handed using the CLI flag. I'm not sure whether that's the only thing that happened, but I guess with a bit of effort one could connect the app to the remote dev server but disable the live reloading.

timvahlbrock avatar Mar 03 '22 07:03 timvahlbrock

To whom it may concern, here is the approach I implemented to enable debugging with source maps support on Android devices

  • install ngx-build-plus by running npx ng add ngx-build-plus This will install the required npm package and update angular.json as required For more details please see https://github.com/manfredsteyer/ngx-build-plus
  • create new file build-customization-plugin.js in the project root directory and add the below content in this file
var merge = require('webpack-merge');

exports.default = {
    config: function (cfg) {
        const strategy = merge.strategy({
            'devtool': 'replace',
        });

        return strategy(cfg, {
            devtool: 'inline-source-map'
        });
    }
}
  • run ng build --eval-source-map --plugin ~build-customization-plugin.js from the root directory to build the project with source maps to debug on Android devices

This is a better approach then changing angular/cli source :)

The above does not work for the latest angular cli (@angular-devkit/* with version 0.1000.0 and above)

To enable this workaround again please update build-customization-plugin.js file in the project root directory to make it look as below

const merge = require('webpack-merge');
const webpack = require("webpack");

exports.default = {
    config: function (cfg) {

        // first, we replace devtool in the webpack used by the angular cli to have the value 'inline-source-map'
        const strategy = merge.strategy({
            'devtool': 'replace',
        });
        const result = strategy(cfg, {
            devtool: 'inline-source-map'
        });

        // then we find SourceMapDevToolPlugin and remove it
        // This is because we should never use both the devtool option and plugin together.
        // The devtool option adds the plugin internally so you would end up with the plugin applied twice.
        // See https://webpack.js.org/configuration/devtool/
        const index = result.plugins.findIndex((plugin) => {
            return plugin instanceof webpack.SourceMapDevToolPlugin;
        });
        result.plugins.splice(index, 1);

        return result;
    }
}

All the rest is the same

No longer working on ionic 6 and Angular 13, is there any updated workaround for this?

LuisMCunha avatar May 15 '22 18:05 LuisMCunha

No longer working on ionic 6 and Angular 13, is there any updated workaround for this?

This one works https://github.com/ionic-team/ionic-framework/issues/16455#issuecomment-505397373

ryaa avatar May 16 '22 04:05 ryaa

No longer working on ionic 6 and Angular 13, is there any updated workaround for this?

This one works #16455 (comment)

Indeed, it works, for some reason if I run the commands individually:

ng run app:ionic-cordova-build --platform=android
node attach-source-maps.js
cordova build android --device
native-run android --app platforms/android/app/build/outputs/apk/debug/app-debug.apk --device

doesn't work, but if I add:

"hooks": { "build:after": "attach-source-maps.js" } to ionic.config.json it does, strange.

Thanks.

LuisMCunha avatar May 16 '22 15:05 LuisMCunha

I've successfully got source maps on my device with following workaround:

add following to your ionic.config.json:

{
  [...],

  "hooks": {
    "build:after": "./attach-source-maps.js"
  }
}

Then create attach-source-maps.js in the root of your project with following content:

let fs = require('fs');
let path = require('path');

const TARGET_DIR = 'www';

module.exports = function (ctx) {
    console.log('=====================');
    console.log('attaching source maps');
    console.log('=====================');

    let files = fs.readdirSync(TARGET_DIR);

    files.forEach(file => {
        let mapFile = path.join(TARGET_DIR, file + '.map');
        let targetFile = path.join(TARGET_DIR, file);
        if (path.extname(file) === '.js' && fs.existsSync(mapFile)) {
            let bufMap = fs.readFileSync(mapFile).toString('base64');
            let bufFile = fs.readFileSync(targetFile, "utf8");
            let result = bufFile.replace('sourceMappingURL=' + file + '.map', 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + bufMap);
            fs.writeFileSync(targetFile, result);
        }
    });
};

At the end adjust script to your needs - eg disable it for prod build

How can I disable this for prod builds? I've been struggling trying to import the environment .ts file into this attach-source-maps.js file, and I can also only use a .js file in the hook.

I've also tried the live-reload option but can't get that to work either, we test mostly on emulators and physical devices connected via a cable - does this methods require a device connected via Wi-Fi?

It's not a huge problem but just a bit annoying to have to enable and disable the hook manually for prod vs dev builds all the time.

Ionic 6 / Angular 13 / Capacitor 3

philkonick avatar Jun 10 '22 08:06 philkonick

I've also tried the live-reload option but can't get that to work either, we test mostly on emulators and physical devices connected via a cable - does this methods require a device connected via Wi-Fi?

The livereload option definitely worked over cable too. However, the host and the device need to be on the same network and able to reach each other.

timvahlbrock avatar Jun 10 '22 08:06 timvahlbrock

@philkonick

How can I disable this for prod builds?

I think that you can:

  1. run the build without using ionic cli/hooks but using angular cli with angular.json to be configured not to include source maps into the production build (should be there by default). Ionic cli uses angular cli under the hood, so you may just want to use it directly.

For example, here is the excerpt for scripts section in my package.json

...
    "build:prod": "ng run app:build:production -nc --output-hashing=none",
    "build:apk": "cd android && ./gradlew clean && ./gradlew assembleRelease",
    "prebuild:prod": "rm -rf sourcemaps",
    "postbuild:prod": "mkdir sourcemaps; mv www/*.map sourcemaps",
    "upload:sourcemaps": "node ./scripts/upload_sourcemaps_to_Rollbar.js",
    "release:android": "npm run build:prod && npx cap sync android && npm run build:apk"
...

You will run the dev build as you do now but for the production build issue npm run release:android

OR

  1. remove the hook from ionic.config.json and run the production build as you do now but for the development build add the extra step to attach sourcemaps, as below
"build:dev:android": "ionic build && node ./scripts/attach-source-maps-for-npm.js && cap copy",

ryaa avatar Jun 10 '22 11:06 ryaa

manually attaching the source code is a pain in nx monorepos :/

distante avatar Aug 02 '22 07:08 distante

In Capacitor 4.1.0 there is now an option that allows debugging the Android Web View in Chrome/Edge. You run: npx cap sync --inline

The argument --inline makes sure the source maps are inlined and you can use chrome://inspect/ or edge://inspect/ to debug into your Typescript code (under the webpack:// tree). debug-android-webview

dtarnawsky avatar Aug 18 '22 22:08 dtarnawsky

Hi everyone,

As @dtarnawsky mentioned in https://github.com/ionic-team/ionic-framework/issues/16455#issuecomment-1220050827, Capacitor 4.1.0 added a new option to inline all source maps when syncing. This makes it possible to get the latest source maps when debugging in a Chromium-based browser. As a result, I am going to close this issue.

See Damian's comment above for more information.

liamdebeasi avatar Aug 22 '22 20:08 liamdebeasi

Hi everyone,

As @dtarnawsky mentioned in #16455 (comment), Capacitor 4.1.0 added a new option to inline all source maps when syncing. This makes it possible to get the latest source maps when debugging in a Chromium-based browser. As a result, I am going to close this issue.

See Damian's comment above for more information.

@liamdebeasi liamdebeasi Thanks for the update! Is it possible to add the 'inline' option also to 'copy' command, for example: "npx cap copy --inline"? I guess that copy command is being used much more often than sync (at least I use it much more for fast sync of the web folder) Since 'inline' related to source maps, I think it's usable to have it in this command. Thanks :)

itziksha avatar Sep 07 '22 06:09 itziksha

Hi there,

I do not work on the Capacitor project, so I am unable to assist with this feature request. I recommend opening a feature request on the Capacitor repo.

liamdebeasi avatar Sep 07 '22 13:09 liamdebeasi

@itziksha : thank-you for bringing that up. I 100% agree with you and started discussing that with the Capacitor team this morning. They have asked me to open an internal Jira ticket for them to track. If you do create a feature request as @liamdebeasi suggested, please let me know and I will attach it to the internal Jira ticket.

kensodemann avatar Sep 07 '22 13:09 kensodemann

@itziksha : thank-you for bringing that up. I 100% agree with you and started discussing that with the Capacitor team this morning. They have asked me to open an internal Jira ticket for them to track. If you do create a feature request as @liamdebeasi suggested, please let me know and I will attach it to the internal Jira ticket.

@kensodemann @liamdebeasi

I opened a feature request here - https://github.com/ionic-team/capacitor/issues/5900

Thanks.

itziksha avatar Sep 07 '22 13:09 itziksha