在webpack.optimize.UglifyJsPlugin之前将es6转换为es5

时间:2017-07-20 18:02:30

标签: webpack babeljs production uglifyjs react-boilerplate

我有webpack应用程序,当我在开发模式下编译它时,一切都很顺利,但是当我在生产模式下编译时,我遇到了这个错误:

[ Error: 2.7e881e81db9016b449f9.chunk.js from UglifyJs
   Unexpected token: name (ptr) [2.7e881e81db9016b449f9.chunk.js:169,6]
   at /home/hossein/d/projects/tPlus/webClient/node_modules/uglifyjs-webpack-plugin/dist/index.js:235:34
   at Array.forEach (native)
   at Compilation.<anonymous> (/home/hossein/d/projects/tPlus/webClient/node_modules/uglifyjs-webpack-plugin/dist/index.js:54:20)
   at Compilation.applyPluginsAsyncSeries (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/node_modules/tapable/lib/Tapable.js:188:13)
   at self.applyPluginsAsync.err (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/lib/Compilation.js:640:10)
   at next (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/node_modules/tapable/lib/Tapable.js:184:11)
   at ExtractTextPlugin.<anonymous> (/home/hossein/d/projects/tPlus/webClient/node_modules/extract-text-webpack-plugin/index.js:316:4)
   at Compilation.applyPluginsAsyncSeries (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/node_modules/tapable/lib/Tapable.js:188:13)
   at sealPart2 (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/lib/Compilation.js:636:9)
   at next (/home/hossein/d/projects/tPlus/webClient/node_modules/webpack/node_modules/tapable/lib/Tapable.js:184:11)
   at ExtractTextPlugin.<anonymous> (/home/hossein/d/projects/tPlus/webClient/node_modules/extract-text-webpack-plugin/index.js:292:5)
   at /home/hossein/d/projects/tPlus/webClient/node_modules/extract-text-webpack-plugin/node_modules/async/lib/async.js:52:16
   at Object.async.forEachOf.async.eachOf (/home/hossein/d/projects/tPlus/webClient/node_modules/extract-text-webpack-plugin/node_modules/async/lib/async.js:236:30)

我发现包含错误的行包含let个关键字。

我知道UglifyJsPlugin不支持ES6,但我还应该怎样做才能将ES6代码转换为ES5。

2.7e881e81db9016b449f9.chunk.js:169处的代码似乎不是我的。

这是我的webpack.prod.bable.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = require('./webpack.base.babel')({
  // In production, we skip all hot-reloading stuff
  entry: [
    'script-loader!jquery/dist/jquery.min.js',
    // 'script!materialize-css/dist/js/materialize.min.js',
    'script-loader!style/js/materialize.js',
    'script-loader!style/js/init.js',
    path.join(process.cwd(), 'app/app.js'),
  ],

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  // We use ExtractTextPlugin so we get a separate CSS file instead
  cssLoaders: 'style-loader!css-loader?localIdentName=[local]__[path][name]__[hash:base64:5]&importLoaders=1',

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      children: true,
      minChunks: 2,
      async: true,
    }),
    function()
    {
      this.plugin("done", function(stats)
      {
        if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1)
        {
          console.log(stats.compilation.errors);
          process.exit(1); // or throw new Error('webpack build failed.');
        }
        // ...
      });
    },
    // OccurrenceOrderPlugin is needed for long-term caching to work properly.
    // See http://mxs.is/googmv
    new webpack.optimize.OccurrenceOrderPlugin(true),

    // Merge all duplicate modules
    new webpack.optimize.DedupePlugin(),

    // Minify and optimize the JavaScript
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false, // ...but do not show warnings in the console (there is a lot of them)
      },
    }),

    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),

    // Extract the CSS into a separate file
    new ExtractTextPlugin('[name].[contenthash].css'),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,

      AppCache: false,
    }),
  ],
});

这是我的webpack.base.babel.sj

/**

*常见的WEBPACK配置      * /

const path = require('path');
const webpack = require('webpack');

// PostCSS plugins
const cssnext = require('postcss-cssnext');
const postcssFocus = require('postcss-focus');
const postcssReporter = require('postcss-reporter');

module.exports = (options) => ({
  entry: options.entry,
  externals: {
    jquery: 'jQuery'
  },
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    rules: [
      {
        test: /\.js$/, // Transform all .js files required somewhere with Babel
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: options.babelQuery,
      }, {
        // Transform our own .css files with PostCSS and CSS-modules
        test: /\.css$/,
        exclude: /node_modules/,
        loader: options.cssLoaders,
      }, {
        // Do not transform vendor's CSS with CSS-modules
        // The point is that they remain in global scope.
        // Since we require these CSS files in our JS or CSS files,
        // they will be a part of our compilation either way.
        // So, no need for ExtractTextPlugin here.
        test: /\.css$/,
        include: /node_modules/,
        loaders: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        loaders: [{
          loader: "style-loader"
        }, {
          loader: "css-loader", options: {
            sourceMap: true
          }
        }, {
          loader: "sass-loader", options: {
            sourceMap: true
          }
        }]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader',
      }, {
        test: /\.(jpg|png|gif)$/,
        loaders: 'file-loader',
      }, {
        test: /\.html$/,
        loader: 'html-loader',
      }, {
        test: /\.json$/,
        loader: 'json-loader',
      }, {
        test: /\.(mp4|webm)$/,
        loader: 'url-loader?limit=10000',
      },
      // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
      {test: /\.tsx?$/, loader: "awesome-typescript-loader"},

      // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      {enforce: "pre", test: /\.js$/, loader: "source-map-loader"}
    ],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports?self.fetch!whatwg-fetch',
      '$': 'jquery',
      'jQuery': 'jquery'
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
  ]),
  resolve: {
    // modulesDirectories: ['app','node_modules'],
    modules: ['node_modules', 'app'],
    extensions: [
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.react.js',
    ],
    mainFields: [
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  stats: false, // Don't show stats in the console
});

修改

这是来自babel config

package.json
"babel": {
  "presets": [
    [
      "latest",
      {
        "es2015": {
          "modules": false
        }
      }
    ],
    "react",
    "stage-0"
  ],
  "env": {
    "production": {
      "only": [
        "app"
      ],
      "plugins": [
        "transform-react-remove-prop-types",
        "transform-react-constant-elements",
        "transform-react-inline-elements"
      ]
    },
    "test": {
      "plugins": [
        "istanbul"
      ]
    }
  }
}

0 个答案:

没有答案