@ngtools/webpack not compiling project code after migrating from Angular4 to Angular7

516 views Asked by At

I migrated angular4 application to Angular7 and resolved the dev and prod builds but AOT build is not transpiling the application code(app.module). The main and polyfill bundle size is only 1 kb each. looking at the output console it seems it is not compiling any module.

webpack.config.js :

/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');
const ngw = require('@ngtools/webpack');

const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

const HMR = helpers.hasProcessFlag('hot');
const AOT = Boolean(process.env.BUILD_AOT) || helpers.hasNpmFlag('aot');
let METADATA = {
  isDevServer: helpers.isWebpackDevServer(),
  HMR
};

const sassConfig = require('./scss-config.common');

console.info(`[BUILD STARTED WITH ${AOT ? 'AOT' : 'WITHOUT AOT'}]`);

module.exports = function (options) {
  const isProd = options.env === 'production';
  const envString = isProd ? 'prod' : 'dev';
  METADATA = Object.assign({}, METADATA, require(`./environment/meta-${envString}`));
  return {

    target: "web",
    
    entry: {
      'polyfills': './src/polyfills.browser.ts',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './src/main.browser.ts'

    },

    resolve: {

      alias: {
        'tslib$': 'tslib/tslib.es6.js',
      },
      
      extensions: ['.ts', '.js', '.json'],

      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    module: {

      rules: [     

        {
          test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
          loader: '@ngtools/webpack'
        },       
        {
          test: /\.css$/,
          use: [
            `to-string-loader${isProd? '' : '?sourceMap'}`,
            `css-loader?${JSON.stringify({ sourceMap: !isProd, importLoaders: 1 })}`,
            'postcss-loader',
          ],
          exclude: [helpers.root('src', 'styles')]
        },
        {
          test: /\.scss$/,
          use: [
            `to-string-loader${isProd? '' : '?sourceMap'}`,
            `css-loader?${JSON.stringify({ sourceMap: !isProd, importLoaders: 2 })}`,
            'postcss-loader',
            {
              loader: 'sass-loader',
              options: {
                includePaths: sassConfig.includePaths,
                sourceMap: !isProd
              }
            }
          ],
          exclude: [helpers.root('src', 'styles')]
        },
        {
          test: /\.html$/,
          // use: { loader: 'html-loader' },
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }
      ],

    },

    plugins: [

      new webpack.ProvidePlugin({
        '__assign': ['tslib', '__assign'],
        '__extends': ['tslib', '__extends'],
      }),

      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      new CheckerPlugin(),

      new ContextReplacementPlugin( /(.+)?angular(\\|\/)core(.+)?/, helpers.root('./src'), {} ),

      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },            
        { from: 'src/meta'}
      ],
        isProd ? { ignore: [ 'mock-data/**/*' ] } : undefined
      ),

      new HtmlWebpackPlugin({
        minify: isProd ? {
          removeComments: true,
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          decodeEntities: true,
          processConditionalComments: true,
        } : false,
        template: 'src/index.html',
        title: METADATA.title,
        metadata: METADATA,
        chunksSortMode: "manual",
        chunks: ['polyfills', 'vendor', 'main'],
        inject: false
      }),

      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      new HtmlElementsPlugin({
        headTags: require('./head-config.common')(envString)
      }),
     
       new LoaderOptionsPlugin({}),

      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new ngw.AngularCompilerPlugin({
        tsConfigPath: helpers.root('tsconfig.webpack.json'),
        entryModule: helpers.root('src', 'app/app.module#AppModule'),
        sourceMap: true,
        skipCodeGeneration: true
      })
    ],

    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false,
      fs: 'empty'
    },

    optimization: {
      splitChunks: {
          cacheGroups: {
            polyfills: {
              name: 'polyfills',
              chunks: (chunk) => {
                return chunk.name === 'polyfills';
              }
            },
            vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendor',
                chunks:  (chunk) => {
                  return chunk.name === 'main';
                }
              }
          }
      }
    }
  };
}

tsconfig.webpack.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noEmit": true,
    "noEmitHelpers": true,
    "importHelpers": true,
    "paths": { "tslib": ["./node_modules/tslib/tslib.d.ts"] },
    "baseUrl": "./",
    "strictNullChecks": false,
    "lib": [
      "es2015",
      "dom"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "hammerjs",
      "node"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.spec.ts",
    "src/**/*.e2e.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "forkChecker": true,
    "useWebpackText": true
  },
  "angularCompilerOptions": {
    "skipMetadataEmit": true,
    "skipTemplateCodegen" : false
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

Angular- V7 Webpack - 4 Node - 8.11.1

1

There are 1 answers

0
Pradeep On

Finally, I managed to resolve this and the root cause was a silly one. As my project is a legacy one so there are many unnecessary configurations and one such was "noEmit: true" in 'compilerOptions' in 'tsconfig.webpack.json' file. After removing this property the artifacts are generating properly.