angular - ng serve --prod for ng-cli 结果在 UglifyJs SyntaxError : Unexpected token: name

标签 angular ecmascript-6 babeljs angular-cli uglifyjs

我正在使用 Angular-CLI (ng-cli) 为我的项目。当我输入 ng serve 时,应用程序运行。但是,当我输入 ng serve --prod 时,出现以下错误。

ERROR in vendor.bundle.js from UglifyJs
SyntaxError: Unexpected token: name (IdUtil) [./~/my-lib/dist/src/common/util.js:7,0][vendor.bundle.js:9318,6]

It is a known issue that UglifyJs cannot parse ES6.

Furthermore, these SO posts (here and here), suggest changing tsconfig.json to target es5. What I am unclear of is whether they mean the tsconfig.json of the consuming Angular project or the one that was used to generate the library. At any rate, my Angular project's tsconfig.json already targets es5. It looks like the following.

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

导入到 Angular 项目中的库的 tsconfig.json 如下所示,它不以 es5 为目标,而是以 es6 为目标。顺便说一句,我不能简单地将此库中的开关从 es6 切换回 es5 (我刚刚尝试过),因为我正在使用 es6 类像 SetMap(这些类的使用非常严格,至少可以说更改它们不是微不足道的;如果我知道这一切,我会已经选择完全避免使用 es6 功能)。

{
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es6",
        "module": "commonjs",
        "alwaysStrict": true,
        "diagnostics": false,
        "listEmittedFiles": false,
        "listFiles": false,
        "pretty": true,
        "declaration": true
    }
}

这是我的问题。

  • 如何在使用 ng serve --prod 时禁用 Angular-CLI 的丑化?
  • 问题出在我的 Angular 项目或导入库的 es5/es6 目标上吗?
  • SO 帖子似乎建议我可以在 Angular-CLI 通过 UglifyJs 为 ng serve --prod 施展魔法之前,通过 babel(我以前从未使用过)预处理导入的库>。该程序是否记录在案?如果是这样,请告诉我该怎么做。 angular-cli.json 是我了解配置 ng-cli 的地方。如果这个建议属实,我无法确定如何 Hook babel 预处理。

最佳答案

您可以使用一些技巧来处理 ES6/ES2015 缩小。

您可以使用 uglifyjs-webpack-plugin by bebraw - 将 UglifyJs 与 webpack 分离。用法如下:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    entry: {...},
    output: {...},
    module: {...},
    plugins: [
        new UglifyJSPlugin()
    ]
};

然后,您必须将 package.json 中的 uglify-js 引用替换为以下内容:

"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony",

关于angular - ng serve --prod for ng-cli 结果在 UglifyJs SyntaxError : Unexpected token: name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41865131/

相关文章:

javascript - babel - es2015 和 es2017 预设不能一起工作

javascript - React.js 转译问题。 Babel 构建命令不起作用

angular - 路由器导航在同一页面时不调用 ngOnInit

css - 如何使 SVG 不拉伸(stretch)?

reactjs - JS引用最佳实践? ES6/React——单引号、双引号、反引号?

javascript - ES6 类中的 ES6 函数、箭头函数和 'this'

javascript - 如何将 RUN 操作绑定(bind)到 Cloud9 中正确的 NodeJS 版本?

javascript - 对 @babel/preset-env 的 useBuiltIns 选项感到困惑(使用 Browserslist 集成)

angular - ngModel 更改,ngModelChange 未被调用

javascript - 如何将输入标签值传递给(点击)函数并在服务 Angular 8 中使用