afterwind-io / preprocessor-loader

Bring the awesome "Conditional Compilation" to the Webpack, and more.
MIT License
40 stars 12 forks source link

Support for Angular Project Generated by Angular CLI #7

Open afterwind-io opened 4 years ago

afterwind-io commented 4 years ago

This issue is the continuous discussion of #6.

TL;DR Currently there is no easy workaround to gracefully apply the preprocessor and keep an accurate source map at the same time.

The real problem here is, during the compilation, Angular just loads all the files from the file system. All content generated by last loader (webpack-preprocessor-loader in this case) is neglected, which means:

angular.json, with @angular-builders/custom-webpack

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "webpack.config.js",
        "mergeStrategies": {
          "module.rules": "append"
        }

...with webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: "webpack-preprocessor-loader",
            options: {
              debug: false,
            }
          },
        // ...

... actually does not work at all.

If we modify the mergeStrategies to prepend, another problem rises. The preprocessor now takes js file, compiled by Angular, as its source. Currently the preprocessor will not pass the source map to the next loader (and it should not, because the preprocessor is meant to deal with the original code directly, thus no source map from upstream). As a result, the source map generated by Angular (js -> ts) is lost. So the final source map we do see in the inspector is a mapping between the bundled file and corresponding compiled code file, which is not intended. But the mapping is accurate though.

Then what about just passing the source map downward? Well, here is the reference from the earlier discussion:

Certain lines of code would likely be cut during preprocessing, and it can leads to potential problems. If source map generated from upstream does exist, it does not "know" the fact that some code will be trimmed afterwards, because the source map itself is based on the processed code from last step. In conclusion, the mapping would be broken and it will create offset after the cuts.

In conclusion, to handle the problem properly, the preprocessor need to generate its own source map, and maybe based on the potential source map from upstream, which is far beyond the intended usage of this loader.

If anyone who is interested and has better idea/workaround, please feel free to leave your solution below. Thank you.