Search code examples
reactjstypescriptwebpackecmascript-6uglifyjs

React + react-router + typescript webpack production bundle issue


I'm building a app using React + react-router + redux + typescript + webpack, here's my tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    },  
    "files": [
        "./src/index.tsx"
    ]
}

And this is my webpack.config.js looks like:

var PROD = JSON.parse(process.env.PROD_ENV || '0');
...
module.exports = {
    ...
    plugins: PROD ? [
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false }
        })
    ] : [],
    ...
    module: {
        loaders: [
            // Sass loader for stylesheet.
            { test: /\.scss$/, loaders: ["style", "css", "sass"], exclude: /node_modules/ },
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            { test: /\.tsx?$/, loaders: ["babel-loader", "ts-loader"], exclude: /node_modules/ },
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, loader: "source-map-loader" }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM",
        "react-router": "ReactRouter",
        "redux": "Redux",
        "react-redux": "ReactRedux"
    },
}

Now if I use webpack to bundle, everything looks fine, but if I run

PROD_ENV=1 webpack

to try to generate uglified js bundle file, it gives me the following error compilation message:

ERROR in ./dist/bundle.js from UglifyJs
SyntaxError: Unexpected token: name (AppRoutes) [./src/routes.tsx:8,0]

Any help would be appreciated! Thanks.


Solution

  • UglifyJS uses it's own ES5 parser. It's quite possible that you parse and transform with Babel, parse and transform with Webpack and still produce source code that is not going to be supported by UglifyJS's parser.

    Usually this means going back to whatever loader produced the input module sources for Webpack and making sure everything is ES5 compliant. Configure {debug: true} for the UglifyJS plugin and find the illegal ES5 syntax in the bundle.

    If your loaders produce the same output in development and production, then you can create a development bundle and run UglifyJS from the command line or paste it to AST Explorer and use the provided uglify-js parser.

    Alternatively, you might try babili and see how that works for you.