ava: SyntaxError: Unexpected token import

流过昼夜 提交于 2019-11-29 16:04:41

问题


So ava comes with build-in ES2015 support, which works fine for my actual test files. However, when I do

import {newUser, createUser, login} from './helpers/user';

I can't use import and export in the helper file, I then get:

Users/rowe/Code/fv/foxvision-api/test/api/helpers/user.js:1
(function (exports, require, module, __filename, __dirname) { import request from 'supertest';

SyntaxError: Unexpected token import

I have no specific babel configuration set up as for the test files it works out of the box. Can anyone explain to me why the helper dependencies are not transpiled with babel? Using test/**/helpers is even following ava convention.

Thanks, Robin

Solution

So based on thangngoc89's solution, what I did to make it work was:

  1. Add a .babelrc with content:
{
  "presets": [
    "es2015",
    "stage-2"
  ],
  "plugins": [
    "espower",
    "transform-runtime"
  ]
}
  1. Added to package.json:
"ava": {
  "require": ["babel-register"],
  "babel": "inherit"
}

回答1:


AVA only transpile the test files. Not test dependencies so you will need to setup babel in your project (I suppose you did it because you're using ES6 anyway).

Then in AVA's setting, add this :

"ava": {
  ...
  "babel": "inherit"
}

It means that use your project babel setting to transpile the test dependencies. See more information in AVA docs: https://github.com/sindresorhus/ava/blob/master/docs/recipes/babelrc.md




回答2:


Using rweng, my solution came out a bit simpler.

  1. .babelrc
{
  "presets": [
    "es2015"
  ],
  "plugins": [
    "transform-runtime"
  ]
}
  1. package.json:
"ava": {
  "require": ["babel-register"],
  "babel": "inherit"
}



回答3:


Unfortunately standard solution didn't work for my case. Here is my solution which worked for ava + quasar + vue project

.babelrc

{
  "presets": [
    "es2017",
    "@ava/stage-4",
    "stage-3"
  ],
  "plugins": [
    "transform-runtime"
  ]
}

package.json

"ava": {
  "require": [
    "babel-register"
  ],
  "babel": "inherit"
},
"scripts": {
  "ava": "NODE_ENV=test ava",
  "test": "ava",
  "test:watch": "ava --watch --verbose"
}

install modules

yarn add babel-register babel-preset-es2017 @ava/babel-preset-stage-4 babel-plugin-transform-runtime babel-preset-stage-3 --dev


来源:https://stackoverflow.com/questions/36720335/ava-syntaxerror-unexpected-token-import

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