React + react-router + typescript webpack生产包问题

时间:2016-11-13 01:42:14

标签: reactjs typescript webpack ecmascript-6 uglifyjs

我正在使用React + react-router + redux + typescript + webpack构建一个应用程序,这是我的tsconfig.json:

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

这是我的webpack.config.js看起来像:

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"
    },
}

现在,如果我使用webpack捆绑,一切看起来都很好,但如果我运行

PROD_ENV=1 webpack

尝试生成uglified js包文件,它给出了以下错误编译消息:

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

任何帮助将不胜感激!感谢。

1 个答案:

答案 0 :(得分:1)

UglifyJS使用它自己的ES5解析器。很可能你使用Babel进行解析和转换,使用Webpack进行解析和转换,并且仍然生成UglifyJS解析器不支持的源代码。

通常这意味着回到为Webpack生成输入模块源的任何加载器并确保一切都符合ES5。为UglifyJS插件配置{debug: true},并在捆绑包中找到非法的ES5语法。

如果您的加载器在开发和生产中产生相同的输出,那么您可以创建开发包并从命令行运行UglifyJS或将其粘贴到AST Explorer并使用提供的uglify-js解析器。 / p>

或者,您可以尝试babili,看看它是如何运作的。