Webpack,删除弹出的Angular CLI应用程序中的注释无效

时间:2017-07-03 11:04:40

标签: angular webpack angular-cli webpack-2 uglifyjs

我有一个弹出的Angular CLI应用程序,它会对UglifyJs设置发出“无论我做什么”的评论。

我遵循了herehere以及各个地方的建议,但似乎都没有。

我不确定在插件顺序中我应该放置UglifyJsPlugin。我已经尝试过第一个位置,最后一个位置,第二个位置,同时在其他任何位置。

其他插件中是否有某些设置会干扰?

我使用"build:prod": "set NODE_ENV=production&&webpack --define process.env.NODE_ENV=\"'production'\""

在Windows上运行此功能
/* eslint-disable node/no-unpublished-require */
/* eslint-disable node/no-extraneous-require */
const path = require('path');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssUrl = require('postcss-url');
const cssnano = require('cssnano');

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

const nodeModules = path.join(process.cwd(), 'node_modules');
const genDirNodeModules = path.join(
  process.cwd(),
  './src',
  '$$_gendir',
  'node_modules');
const entryPoints = [
  'inline', 'polyfills', 'sw-register', 'scripts', 'styles', 'vendor', 'main'];
const minimizeCss = false;
const baseHref = '';
const deployUrl = '';
// safe settings based on: https://github.com/ben-eb/cssnano/issues/358#issuecomment-283696193:
const postcssPlugins = function() {
  // const importantCommentRe =
  //   /@preserve|@license|[@#]\s*source(?:Mapping)?URL|^!/i;
  const minimizeOptions = {
    autoprefixer: false,
    safe: true,
    mergeLonghand: false,
    discardComments: {
      remove: (comment) => true,
      // !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 isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  'devtool': 'none', // 'source-map',
  'resolve': {
    'extensions': [
      '.ts',
      '.js',
    ],
    'modules': [
      './node_modules',
      './node_modules',
    ],
  },
  'resolveLoader': {
    'modules': [
      './node_modules',
    ],
  },
  'entry': {
    'main': [
      './src\\main.ts',
    ],
    'polyfills': [
      './src\\polyfills.ts',
    ],
    'scripts': [
      'script-loader!./node_modules\\moment\\min\\moment.min.js',
      'script-loader!./node_modules\\pptxgenjs\\dist\\pptxgen.js',
      'script-loader!./node_modules\\pptxgenjs\\dist\\pptxgen.shapes.js',
      'script-loader!./node_modules\\pptxgenjs\\libs\\jszip.min.js',
      'script-loader!./node_modules\\pptxgenjs\\libs\\jquery.min.js',
    ],
    'styles': [
      './src\\styles.scss',
    ],
  },
  'output': {
    'path': path.join(process.cwd(), 'dist'),
    'filename': '[name].bundle.js',
    'chunkFilename': '[id].chunk.js',
  },
  'module': {
    'rules': [
      // {
      //   '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|gif|otf|ttf|woff|woff2|cur|ani)$/,
        'loader': 'url-loader?name=[name].[hash:20].[ext]&limit=10000',
      },
      {
        'exclude': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.css$/,
        'use': [
          'exports-loader?module.exports.toString()',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
        ],
      },
      {
        'exclude': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.scss$|\.sass$/,
        'use': [
          'exports-loader?module.exports.toString()',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'sass-loader',
            'options': {
              'sourceMap': false,
              'precision': 8,
              'includePaths': [],
            },
          },
        ],
      },
      {
        'exclude': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.less$/,
        'use': [
          'exports-loader?module.exports.toString()',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'less-loader',
            'options': {
              'sourceMap': false,
            },
          },
        ],
      },
      {
        'exclude': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.styl$/,
        'use': [
          'exports-loader?module.exports.toString()',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'stylus-loader',
            'options': {
              'sourceMap': false,
              'paths': [],
            },
          },
        ],
      },
      {
        'include': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.css$/,
        'use': [
          'style-loader',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
        ],
      },
      {
        'include': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.scss$|\.sass$/,
        'use': [
          'style-loader',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'sass-loader',
            'options': {
              'sourceMap': false,
              'precision': 8,
              'includePaths': [],
            },
          },
        ],
      },
      {
        'include': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.less$/,
        'use': [
          'style-loader',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'less-loader',
            'options': {
              'sourceMap': false,
            },
          },
        ],
      },
      {
        'include': [
          path.join(process.cwd(), 'src\\styles.scss'),
        ],
        'test': /\.styl$/,
        'use': [
          'style-loader',
          {
            'loader': 'css-loader',
            'options': {
              'sourceMap': false,
              'importLoaders': 1,
            },
          },
          {
            'loader': 'postcss-loader',
            'options': {
              'ident': 'postcss',
              'plugins': postcssPlugins,
            },
          },
          {
            'loader': 'stylus-loader',
            'options': {
              'sourceMap': false,
              'paths': [],
            },
          },
        ],
      },
      {
        'test': /\.ts$/,
        'loader': '@ngtools/webpack',
      },
    ],
  },
  'plugins': [
    new NoEmitOnErrorsPlugin(),
    new UglifyJsPlugin({
      comments: false,
      sourceMap: false,
      compress: {
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true,
      },
      // mangle: {
      //   except: ['$super', '$', 'exports', 'require'],
      // },
      output: {
        comments: false,
      },
    }),
    new GlobCopyWebpackPlugin({
      'patterns': [
        'assets',
        'favicon.ico',
      ],
      'globOptions': {
        'cwd': 'c:\\dev\\engage\\js-engage\\src',
        'dot': true,
        'ignore': '**/.gitkeep',
      },
    }),
    new ProgressPlugin(),
    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({
      'name': 'inline',
      'minChunks': null,
    }),
    new CommonsChunkPlugin({
      'name': 'vendor',
      'minChunks': (module) => module.resource &&
      (module.resource.startsWith(nodeModules) || module.resource.startsWith(
        genDirNodeModules)),
      'chunks': [
        'main',
      ],
    }),
    new AotPlugin({
      'mainPath': 'main.ts',
      'hostReplacementPaths': {
        'environments\\environment.ts': isProduction
          ? 'environments\\environment.prod.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,
  },
};

更新

而不是'none',这是错误的,我设置devtools: false ,但它没有帮助。

此外,我尝试了remove-comments-loaderwebpack-comment-remover-loader,但都没有帮助。

实际上我刚刚意识到这些评论出现在main.bundle.js.map中 - 即使我关闭了文件被保留的源地图。当我手动删除预先存在的地图并且删除了源地图的新版本时,它们没有被重新制作,并且javascript文件中没有没有评论

Tl; dr:用户错误。关闭源地图,删除任何预先存在的源地图,重建。

1 个答案:

答案 0 :(得分:0)

这是webpack.config.js档案。进行相关更改。

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

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

const nodeModules = path.join(process.cwd(), 'node_modules');
const entryPoints = ["inline","polyfills","sw-register","styles","vendor","main"];




module.exports = {
  "devtool": "source-map",
  "resolve": {
    "extensions": [
      ".ts",
      ".js"
    ],
    "modules": [
      "./node_modules"
    ]
  },
  "resolveLoader": {
    "modules": [
      "./node_modules"
    ]
  },
  "entry": {
    "main": [
      "./src\\main.ts"
    ],
    "polyfills": [
      "./src\\polyfills.ts"
    ],
    "styles": [
      "./src\\styles.css"
    ]
  },
  "output": {
    "path": path.join(process.cwd(), "dist"),
    "filename": "[name].bundle.js",
    "chunkFilename": "[id].chunk.js"
  },
  "module": {
    "rules": [
      {
        "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].[ext]"
      },
      {
        "test": /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/,
        "loader": "url-loader?name=[name].[ext]&limit=10000"
      },
      {
        "exclude": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.css$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "sass-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.less$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "less-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.styl$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
        ]
      },
      {
        "include": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.css$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "sass-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.less$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "less-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src\\styles.css")
        ],
        "test": /\.styl$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "test": /\.ts$/,
        "loader": "@ngtools/webpack",
        "exclude": [
          /\.(spec|e2e)\.ts$/
        ]
      }
    ]
  },
  "plugins": [
    new NoEmitOnErrorsPlugin(),
    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({
      "name": "inline",
      "minChunks": null
    }),
    new CommonsChunkPlugin({
      "name": "vendor",
      "minChunks": (module) => module.resource && module.resource.startsWith(nodeModules),
      "chunks": [
        "main"
      ]
    }),
    new GlobCopyWebpackPlugin({
      "patterns": [
        "assets",
        "favicon.ico"
      ],
      "globOptions": {
        "cwd": "D:\\Webpack\\demo\\src",
        "dot": true,
        "ignore": "**/.gitkeep"
      }
    }),
    new ProgressPlugin(),
    new ExtractTextPlugin({
      "filename": "[name].bundle.css",
      "disable": true
    }),
    new LoaderOptionsPlugin({
      "sourceMap": false,
      "options": {
        "postcss": [
          autoprefixer()
        ],
        "sassLoader": {
          "sourceMap": false,
          "includePaths": []
        },
        "lessLoader": {
          "sourceMap": false
        },
        "context": ""
      }
    }),
    new AotPlugin({
      "tsConfigPath": "src\\tsconfig.json",
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments\\environment.ts": "environments\\environment.ts"
      },
      "exclude": [
        "**/*.spec.ts",
        "D:\\Webpack\\demo\\src\\test.ts"
      ],
      "skipCodeGeneration": true
    })
  ],
  "node": {
    "fs": "empty",
    "global": true,
    "crypto": "empty",
    "tls": "empty",
    "net": "empty",
    "process": true,
    "module": false,
    "clearImmediate": false,
    "setImmediate": false
  }
};

希望,这会有所帮助!