SyntaxError: Unexpected token 'const' for testing.es5.js

时光怂恿深爱的人放手 提交于 2019-11-29 16:50:55

I just created a basic Angular project and had the same (or similar) issue with PhantomJS integration.

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  SyntaxError: Unexpected token 'const'
  at webpack:///src/app/app.component.ts:1:0 <- src/test.ts:63184

Our team got it to work and here's what we tossed in our documentation:

PhantomJS is a headless (aka, no GUI) browser that can be used for automated testing. Currently, PhantomJS has a limitation in that it only supports the ES5 standard.

  1. npm install -g phantomjs-prebuilt
  2. npm install --save-dev karma-phantomjs-launcher
    • in karma.conf.js
      1. add require('karma-phantomjs-launcher') to the plugins section
      2. add PhantomJS to the browsers
  3. npm install --save intl
    • in src/polyfill.ts
      1. add import 'intl'; (uncomment at the bottom)
      2. add import "core-js/client/shim"; to the Evergreen requirements section
  4. In src/tsconfig.spec.json (or whatever typescript config is used for tests)
    • Set the target to es5.

Assuming all goes well, testing should work.

Some examples on how to trigger a test run:

  • ng test --browsers PhantomJS --singleRun true
  • ./node_modules/karma/bin/karma start ./karma.conf.js --browsers PhantomJS --singleRun true

As you're using @angular/cli: 1.0.0-rc.1 I think you have a tsconfig.json looking like that :

{
  "compileOnSave": false,
  "compilerOptions": {
    ...
    "target": "es5",
    "module": "es2015",
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

And you should also have a tsconfig.e2e.json in your E2E folder :

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../dist/out-tsc-e2e",
    "module": "commonjs",
    "target": "es6",
    "types":[
      "jasmine",
      "node"
    ]
  }
}

Simply remove the line "target": "es6" and as this files extends the previous one, you'll end up compiling your app in ES5.

It should work after that.

In my case, tests were failing after updating karma.config.js to use PhantomJS launcher.

To sort the issue, updated src/tsconfig.spec.json to use ES5 instead of ES6.

{
    ...
    "target": "es5",
    ...
}

And in my case it was due to a rogue import that webpack didn't like too much, or rather didn't know how to do deal with it:

import {HttpClient} from "selenium-webdriver/http";

Replacing with the correct HttpClient (our own) solved the issue. The issue was that the JS file was actually referring to the "const" keyword, however I believe that is an ES6 reserved word and not a ES5 reserved one, hence our error. If you get something similar, then you are referring to library where the down compiler hasn't spotted that you want any conversion.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!