0

我将 angular4 应用程序迁移到 Angular7 并解决了 dev 和 prod 构建,但 AOT 构建没有转换应用程序代码(app.module)。主包和 polyfill 包大小各只有 1 kb。查看输出控制台,它似乎没有编译任何模块。

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 节点 - 8.11.1

4

1 回答 1

-1

最后,我设法解决了这个问题,根本原因是愚蠢的。由于我的项目是一个遗留项目,因此有许多不必要的配置,其中一个是 'tsconfig.webpack.json' 文件中的 'compilerOptions' 中的“noEmit: true”。删除此属性后,工件正在正确生成。

于 2019-10-22T08:42:57.970 回答