Gustavo Yance
Gustavo Yance

Reputation: 101

Webpack production build: Unexpected token

I have been trying to deploy my production build with webpack but I can't get it done. I almost read and tried everything and can't make it work. This is the last error that I have: enter image description here

My webpack configuration looks like this:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname, 'src');
const buildPath = path.join(__dirname, 'dist');

    module.exports = {
        devtool: 'cheap-module-source-map',
        entry: {
            // base: path.resolve(staticSourcePath, 'src/sass/base.scss'),
            app: path.resolve(sourcePath, 'index.prod.jsx')
        },
        output: {
            path: path.join(__dirname, 'dist'),
            filename: '[name].[chunkhash].js',
            publicPath: '/'
        },
        resolve: {
            extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
            modules: [
                sourcePath,
                path.resolve(__dirname, 'node_modules')
            ]
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify('production')
            }),
            new webpack.optimize.ModuleConcatenationPlugin(),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                filename: 'vendor.[chunkhash].js',
                minChunks(module) {
                    return module.context && module.context.indexOf('node_modules') >= 0;
                }
            }),

            new UglifyJsPlugin({
                sourceMap: true,
                uglifyOptions: {
                    ecma: 8,
                    compress: {
                        warnings: false
                    }
                }
            }),
            new webpack.LoaderOptionsPlugin({
                options: {
                    postcss: [
                        autoprefixer({
                            browsers: [
                                'last 3 version',
                                'ie >= 10'
                            ]
                        })
                    ],
                    context: staticSourcePath
                }
            }),
            new webpack.HashedModuleIdsPlugin(),
            new HtmlWebpackPlugin({
                template: path.join(__dirname, 'src', 'index.html'),
                path: buildPath,
                excludeChunks: ['base'],
                // filename: 'index.html',
                minify: {
                    collapseWhitespace: true,
                    collapseInlineTagWhitespace: true,
                    removeComments: true,
                    removeRedundantAttributes: true
                }
            }),
            new PreloadWebpackPlugin({
                rel: 'preload',
                as: 'script',
                include: 'all',
                fileBlacklist: [/\.(css|map)$/, /base?.+/]
            }),
            new ScriptExtHtmlWebpackPlugin({
                defaultAttribute: 'defer'
            }),
            new ExtractTextPlugin({
                filename: '[name].[contenthash].css',
                allChunks: true
            }),
            new CompressionPlugin({
                asset: '[path].gz[query]',
                algorithm: 'gzip',
                test: /\.js$|\.jsx$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
                threshold: 10240,
                minRatio: 0.8
            })
        ],
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader']
                },
                {
                    test: /\.(png|jp(e*)g|svg)$/,
                    use: [{
                        loader: 'url-loader',
                        options: {
                            limit: 8000, // Convert images < 8kb to base64 strings
                            name: 'images/[hash]-[name].[ext]'
                        }
                    }]
                },

                {
                    test: /\.(js|jsx)$/,
                    loader: "babel-loader",
                    exclude: /node_modules/,
                    query: {
                        presets: ["es2015", "react", "env"],
                        plugins: [
                            "transform-object-rest-spread",
                            "transform-class-properties"
                        ]
                    }
                },

                {
                    test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
                    use: 'file-loader?name=assets/[name]-[hash].[ext]'
                },
                {
                    test: /\.(png|gif|jpg|svg)$/,
                    use: [
                        'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
                    ],
                    include: staticSourcePath
                }
            ]
        }
    };

I tried changing the presets of babel. I don't know if it could be a problem with the library query-string but even when I don't use it the error persists. I also tried almost all configurations from https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/104 and can't make it work :C....

I hope someone can help me I have been fighting with this error since weekend and im near to kill myself T_T

Upvotes: 4

Views: 5288

Answers (3)

Kiryl Anokhin
Kiryl Anokhin

Reputation: 459

Sometimes such a problem may be a result of the non-transpiled packages (excluded from transpiling).

To solve this you should include these packages to transpiled code:

rules: [
...
test: /\.jsx?$/,
exclude(resource) {
  return (
    /node_modules/.test(resource)
    && !/node_modules\/(query-string|strict-uri-encode|split-on-first)/.test(resource)
  );
},
...
]

Upvotes: 0

Atav32
Atav32

Reputation: 1812

In my experience, it's usually Uglify being too aggressive.

I noticed that in your answer, you've swapped out Uglify for compression-webpack-plugin. That's probably what made the bug go away.


In your original package.json, I'd change the Uglify config to

new UglifyJsPlugin({
  sourceMap:true,
  cache: true,
  parallel: true,
  uglifyOptions:{
    ecma:8
  }
}),

First, you want to see Uglify's warnings. It'll tell you if there's code that's likely to get clobbered by the minification / obfuscation algorithm. If there are, you may have to play with the compress, mangle, toplevel or keep_fnames options depending on how your code is structured. https://github.com/mishoo/UglifyJS2#minify-options

I understand that this might show a lot of warnings from 3rd party libraries. There's a couple things you can do:

  1. Find alternative libs that minify correctly (they'll probably be higher quality anyways).
  2. Import the already minified versions of the lib from /dist instead of from /src and then exclude the lib from the Uglify plugin

The settings for cache and parallel just make the minification run a bit faster.

Upvotes: 1

Gustavo Yance
Gustavo Yance

Reputation: 101

Already tried babel-polyfill and dont work :(

Just updated to webpack 4 and solved my problem. To many people have this kind of error with webpack < 4. I will leave my webpack 4 configuration here for those who had suffered like me

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  entry: ["babel-polyfill", "./src/index.js"],
  resolve: {
    extensions: ['.js', '.jsx']
  },

  output: {
    publicPath: '/'
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.(png|jp(e*)g|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 8000, // Convert images < 8kb to base64 strings
            name: 'images/[hash]-[name].[ext]'
          }
        }]
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true }
          }
        ]
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      }
    ]
  },
  devServer: {
    // host: '0.0.0.0', /******* Para ver en lan*/
    // disableHostCheck: true,/****** Para ver en lan */
    historyApiFallback: true,
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
      threshold: 10240,
      minRatio: 0.8
    })
  ]
};

package.json

"scripts": {
    "start": "webpack-dev-server --mode development --open",
    "build": "webpack --mode production"
  },
     "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.4",
        "babel-plugin-transform-class-properties": "^6.24.1",
        "babel-plugin-transform-object-rest-spread": "^6.26.0",
        "babel-plugin-transform-regenerator": "^6.26.0",
        "babel-preset-env": "^1.6.1",
        "babel-preset-react": "^6.24.1",
        "compression-webpack-plugin": "^1.1.11",
        "css-loader": "^0.28.11",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.0.7",
        "mini-css-extract-plugin": "^0.2.0",
        "react": "^16.3.0",
        "react-dom": "^16.3.0",
        "url-loader": "^1.0.1",
        "webpack": "^4.2.0",
        "webpack-cli": "^2.0.12",
        "webpack-dev-server": "^3.1.1"
      },

.babelrc

{
    "presets": [
        "env",
        "react"
    ],
    "plugins": [
        "transform-object-rest-spread",
        "transform-class-properties",
        "transform-regenerator"
    ]
}

Upvotes: 1

Related Questions