【问题标题】:React + react-router + typescript webpack production bundle issueReact + react-router + typescript webpack 生产包问题
【发布时间】:2017-03-26 23:09:00
【问题描述】:

我正在使用 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]

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

【问题讨论】:

  • ./src/routes.tsx 是什么样的?

标签: reactjs typescript webpack ecmascript-6 uglifyjs


【解决方案1】:

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

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

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

或者,您可以尝试babili,看看它对您有什么作用。

【讨论】: