Search code examples
angularwebpackweb-development-serverangular13source-code-protection

Angular source code not generating only for a few files, for some files its generating


I am trying to debug my application, we have recently upgraded our application to angular 13, the source codes weren't available in the developer tools for chrome, so I have added the sourceCode:true under the default configuration inside the angular.json files, for both the configuration object and the serve object there, for the ng serve

 "development": {
              "buildOptimizer": false,
              "sourceMap": true,
 "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "myapp:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "myapp:build:production"
            },
            "development":{
              "browserTarget": "myapp:build:development"
            }
          },
          "defaultConfiguration": "development"

With this I started getting some of the source code in ng serve local environment but still a vast majority of the files are not giving the source code. Already tried with using new node versions, installing updated angular cli, and verifying tsConfig compiler options

"compilerOptions": {
    "allowJs": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,

I am still not getting the SOURCE CODE FOR SOME OF THE FILES, FOR SOME FILES I AM GETTING THE SOURCE CODE.

Please don't mark this as duplicate, and any and every help is deeply appreciated

NOTE: WE ARE USING WEBPACK

I have tried already with the sourceCode Enabled in the angular.json,

const fs = require('fs');
const path = require('path');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssUrl = require('postcss-url');
const cssnano = require('cssnano');


const {
  NoEmitOnErrorsPlugin,
  SourceMapDevToolPlugin,
  NamedModulesPlugin,
  ContextReplacementPlugin
} = require('webpack');
const {
  GlobCopyWebpackPlugin,
  BaseHrefWebpackPlugin
} = require('@angular/cli/plugins/webpack');
const {
  CommonsChunkPlugin
} = require('webpack').optimize;
const {
  AotPlugin
} = require('@ngtools/webpack');

const nodeModules = path.join(process.cwd(), 'node_modules');
const realNodeModules = fs.realpathSync(nodeModules);
const genDirNodeModules = path.join(process.cwd(), 'src', '$$_gendir', 'node_modules');
const entryPoints = ["inline", "polyfills", "sw-register", "styles", "vendor", "main"];
const minimizeCss = false;
const baseHref = "";
const deployUrl = "";
const postcssPlugins = function () {
  // safe settings based on: https://github.com/ben-eb/cssnano/issues/358#issuecomment-283696193
  const importantCommentRe = /@preserve|@license|[@#]\s*source(?:Mapping)?URL|^!/i;
  const minimizeOptions = {
    autoprefixer: false,
    safe: true,
    mergeLonghand: false,
    discardComments: {
      remove: (comment) => !importantCommentRe.test(comment)
    }
  };
  return [
    postcssUrl({
      url: (URL) => {
        // Only convert root relative URLs, which CSS-Loader won't process into require().
        if (!URL.startsWith('/') || URL.startsWith('//')) {
          return URL;
        }
        if (deployUrl.match(/:\/\//)) {
          // If deployUrl contains a scheme, ignore baseHref use deployUrl as is.
          return `${deployUrl.replace(/\/$/, '')}${URL}`;
        } else if (baseHref.match(/:\/\//)) {
          // If baseHref contains a scheme, include it as is.
          return baseHref.replace(/\/$/, '') +
            `/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
        } else {
          // Join together base-href, deploy-url and the original URL.
          // Also dedupe multiple slashes into single ones.
          return `/${baseHref}/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
        }
      }
    }),
    autoprefixer(),
  ].concat(minimizeCss ? [cssnano(minimizeOptions)] : []);
};


// const styles = [
//   "./src/styles.scss"
// ];

// const entryStyles = [
//   "./src/styles.scss",
//   "./src/assets/semantic-ui/semantic.css"
// ];

const entryStyles = [
  "./node_modules/primeng/resources/themes/omega/theme.css",
  "./node_modules/primeng/resources/primeng.min.css",
  "./node_modules/tinymce/skins/lightgray/skin.min.css",
  "./node_modules/tinymce/skins/lightgray/content.min.css",
  "./src/styles.scss",
];

const tinyscripts = [
//   "./src/app/shared/tinymce-dependencies/tinymce.min.js",
// "./src/app/shared/tinymce-dependencies/charmap.plugin.js",
// "./src/app/shared/tinymce-dependencies/link.plugin.js",
// "./src/app/shared/tinymce-dependencies/list.plugin.js",
// "./src/app/shared/tinymce-dependencies/noneditable.plugin.js",
// "./src/app/shared/tinymce-dependencies/textcolor.plugin.js",
// "./src/app/shared/components/tinymce-editor/modern.theme.js"
  "./node_modules/tinymce/jquery.tinymce.js",
  "./node_modules/tinymce/tinymce.min.js",
  "./node_modules/tinymce/themes/mobile/theme.js",
  "./node_modules/tinymce/themes/modern/theme.js",
];

const stylesPaths = entryStyles.map(function (s) {
  return path.join(process.cwd(), s.slice(2));
})


module.exports = {
  "resolve": {
    "extensions": [
      ".ts",
      ".js"
    ],
    "modules": [
      "./node_modules",
      "./node_modules"
    ],
    "fallback": {
      util: require.resolve("util/")
    },
    "alias": {
      process: "process/browser"
   } ,
    "symlinks": true
  },
  "resolveLoader": {
    "modules": [
      "./node_modules",
      "./node_modules"
    ]
  },
  "entry": {
    "main": [
      "./src/main.ts"
    ],
    "polyfills": [
      "./src/polyfills.ts"
    ],
    "styles": entryStyles,
    "tinyscripts": tinyscripts,
  },
  "output": {
    "path": path.join(process.cwd(), "dist"),
    "filename": "[name].[hash:20].bundle.js",
    "chunkFilename": "[id].[hash:20].chunk.js"
  },
  "module": {
    "rules": [{
        "test": /\.pug$/,
        "loader": ['raw-loader', 'pug-html-loader']
      },
      {
        "enforce": "pre",
        "test": /\.js$/,
        "loader": "source-map-loader",
        "exclude": [
          /\/node_modules\//
        ]
      },
      {
        "test": /\.json$/,
        "loader": "json-loader"
      },
      {
        "test": /\.html$/,
        "loader": "raw-loader"
      },
      {
        "test": /\.(eot|svg)$/,
        "loader": "file-loader?name=[name].[hash:20].[ext]"
      },
      {
        "test": /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|cur|ani)$/,
        "loader": "url-loader?name=[name].[hash:20].[ext]&limit=10000"
      },
      {
        "exclude": stylesPaths,
        "test": /\.css$/,
        "use": [
          "exports-loader?module.exports.toString()",
          {
            "loader": "css-loader",
            "options": {
              "sourceMap": true,
              "importLoaders": 1
            }
          },
          {
            "loader": "postcss-loader",
            "options": {
              "ident": "postcss",
              "plugins": postcssPlugins
            }
          }
        ]
      },
      {
        "exclude": stylesPaths,
        "test": /\.scss$|\.sass$/,
        "use": [
          "exports-loader?module.exports.toString()",
          {
            "loader": "css-loader",
            "options": {
              "sourceMap": true,
              "importLoaders": 1
            }
          },
          {
            "loader": "postcss-loader",
            "options": {
              "ident": "postcss",
              "plugins": postcssPlugins
            }
          },
          {
            "loader": "sass-loader",
            "options": {
              "sourceMap": true,
              "precision": 8,
              "includePaths": []
            }
          }
        ]
      },
      {
        "exclude": stylesPaths,
        "test": /\.less$/,
        "use": [
          "exports-loader?module.exports.toString()",
          {
            "loader": "css-loader",
            "options": {
              "sourceMap": true,
              "importLoaders": 1
            }
          },
          {
            "loader": "postcss-loader",
            "options": {
              "ident": "postcss",
              "plugins": postcssPlugins
            }
          },
          {
            "loader": "less-loader",
            "options": {
              "sourceMap": true
            }
          }
        ]
      },
      {
        "exclude": stylesPaths,
        "test": /\.styl$/,
        "use": [
          "exports-loader?module.exports.toString()",
          {
            "loader": "css-loader",
            "options": {
              "sourceMap": true,
              "importLoaders": 1
            }
          },
          {
            "loader": "postcss-loader",
            "options": {
              "ident": "postcss",
              "plugins": postcssPlugins
            }
          },
          {
            "loader": "stylus-loader",
            "options": {
              "sourceMap": true,
              "paths": []
            }
          }
        ]
      },
      {
        "include": stylesPaths,
        "test": /\.css$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [{
              "loader": "css-loader",
              "options": {
                "sourceMap": true,
                "importLoaders": 1
              }
            },
            {
              "loader": "postcss-loader",
              "options": {
                "ident": "postcss",
                "plugins": postcssPlugins
              }
            }
          ],
          "publicPath": "/feedback/"
        })
      },
      {
        "include": stylesPaths,
        "test": /\.scss$|\.sass$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [{
              "loader": "css-loader",
              "options": {
                "sourceMap": true,
                "importLoaders": 1
              }
            },
            {
              "loader": "postcss-loader",
              "options": {
                "ident": "postcss",
                "plugins": postcssPlugins
              }
            },
            {
              "loader": "sass-loader",
              "options": {
                "sourceMap": true,
                "precision": 8,
                "includePaths": []
              }
            }
          ],
          "publicPath": "/feedback/"
        })
      },
      {
        "include": stylesPaths,
        "test": /\.less$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [{
              "loader": "css-loader",
              "options": {
                "sourceMap": true,
                "importLoaders": 1
              }
            },
            {
              "loader": "postcss-loader",
              "options": {
                "ident": "postcss",
                "plugins": postcssPlugins
              }
            },
            {
              "loader": "less-loader",
              "options": {
                "sourceMap": true
              }
            }
          ],
          "publicPath": "/feedback/"
        })
      },
      {
        "include": stylesPaths,
        "test": /\.styl$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [{
              "loader": "css-loader",
              "options": {
                "sourceMap": true,
                "importLoaders": 1
              }
            },
            {
              "loader": "postcss-loader",
              "options": {
                "ident": "postcss",
                "plugins": postcssPlugins
              }
            },
            {
              "loader": "stylus-loader",
              "options": {
                "sourceMap": true,
                "paths": []
              }
            }
          ],
          "publicPath": "/feedback/"
        })
      },
      {
        "test": /\.ts$/,
        "loader": "@ngtools/webpack"
      }
    ]
  },
  "plugins": [
    new NoEmitOnErrorsPlugin(),
    new GlobCopyWebpackPlugin({
      "patterns": [
        "assets",
        "favicon.ico"
      ],
      "globOptions": {
        "cwd": path.join(process.cwd(), "src"),
        "dot": true,
        "ignore": "**/.gitkeep"
      }
    }),
    new ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new ProgressPlugin(),
    new ExtractTextPlugin({
      "filename": "[name].bundle.css"
    }),
    new HtmlWebpackPlugin({
      "template": "./src/index.html",
      "filename": "./index.html",
      "hash": false,
      "inject": true,
      "compile": true,
      "favicon": false,
      "minify": false,
      "cache": true,
      "showErrors": true,
      "chunks": "all",
      "excludeChunks": [],
      "title": "Webpack App",
      "xhtml": true,
      "chunksSortMode": function sort(left, right) {
        let leftIndex = entryPoints.indexOf(left.names[0]);
        let rightindex = entryPoints.indexOf(right.names[0]);
        if (leftIndex > rightindex) {
          return 1;
        } else if (leftIndex < rightindex) {
          return -1;
        } else {
          return 0;
        }
      }
    }),
    new BaseHrefWebpackPlugin({}),
    new CommonsChunkPlugin({
      "minChunks": 2,
      "async": "common"
    }),
    new CommonsChunkPlugin({
      "name": [
        "inline"
      ],
      "minChunks": null
    }),
    new CommonsChunkPlugin({
      "name": [
        "vendor"
      ],
      "minChunks": (module) => {
        return module.resource &&
          (module.resource.startsWith(nodeModules) ||
            module.resource.startsWith(genDirNodeModules) ||
            module.resource.startsWith(realNodeModules));
      },
      "chunks": [
        "main"
      ]
    }),
    new SourceMapDevToolPlugin({
      "filename": "[file].map[query]",
      "moduleFilenameTemplate": "[resource-path]",
      "fallbackModuleFilenameTemplate": "[resource-path]?[hash]",
      "sourceRoot": "webpack:///"
    }),
    new NamedModulesPlugin({}),
    new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/environment.ts": "environments/environment.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json",
      "skipCodeGeneration": true
    })
  ],
  "node": {
    "fs": "empty",
    "global": true,
    "crypto": "empty",
    "tls": "empty",
    "net": "empty",
    "process": true,
    "module": false,
    "clearImmediate": false,
    "setImmediate": false
  },
  "devServer": {
    "historyApiFallback": true,
    "disableHostCheck": true
  }
};

Solution

  • This is for anyone facing similar issue. I resolved the issue myself, the problem is that the source maps are being generated but they were not visible when we search for the file or when we browse it through the chrome developer tool.

    What worked in my case was "adding a console.log() any statement"

    that gives us the line where the line in the console tab of chrome developer tools,

    and from there if you click on the filename displayed there, you will be directed to the source map of the file, and will also load that file with its source maps in the chrome developer tools

    here clicking on the component name takes you to desired location.