Запуск Nighwatch.js с Babel 7 @ babel / регистрация - PullRequest
0 голосов
/ 18 июня 2019

У меня есть client репозиторий с React 15.3, Webpack 4 и Babel 7. Webpack работает, как чудо, но наш комплект тестирования E2E с использованием Nightwatch 0.9.20 не может скомпилироваться с новым пакетом @babel/register.

Наша компания обновляет нашу версию babel с 6 до 7.

Плавающее по Интернету решение, добавляющее в файл babel.config.js следующее:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": "commonjs",
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    "add-module-exports",
  ]
}

В нашемНапример, это решение не решает нашу проблему.

Я должен отметить, что структура проекта выглядит следующим образом:

client // where nightwatch is run from the terminal
  |-- tests // our E2E tests
  |-- nightwatch.conf.js
  |-- nighwatch_globals.js
  |-- babel.config.js

api // a completely separate repository
  |-- tests // we store factory definitions here as well
  |-- db
       |-- models // also a frequently referenced directory in our E2E tests

Наша структура nightwatch.conf.js выглядит следующим образом:

require('@babel/register')(); // this has been upgraded from 'babel-register'
require('dotenv').config();

...

module.exports = {
  // nightwatch configurations

  "globals_path": "./nightwatch_globals.js",

  // more nightwatch configurations
}

Наш nightwatch_globals.js файл (где вызывается ошибка выглядит так:

import fetch from 'isomorphic-fetch';

module.exports = {
  reporter: function(results, cb) {
    fetch('http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer').then(() => {
      cb();
      if (
        (typeof(results.failed) === 'undefined' || results.failed === 0) &&
          (typeof(results.error) === 'undefined' || results.error === 0)
      ) {
          process.exit(0);
      } else {
          process.exit(1);
      }
    });
  },
  // give the db some time to finish ops from previous test before
  // clearing db and starting the next test
  before: function(done) {
    require('./../eka-api/test/factories/index.js');
    done();
  },
  beforeEach: function(done) {
    setTimeout(function() {
      done();
    }, 5000);
  },
};

А наш babel.config.js файл выглядит следующим образом:


module.exports = function(api) {
  api.cache(true);

  const presets = [
    "@babel/preset-env",
    "@babel/react",
    "@babel/preset-flow",
  ];

  const plugins = [
    "@babel/plugin-syntax-flow",
    "@babel/transform-flow-strip-types",
    ["@babel/plugin-proposal-decorators", {"legacy": true}],
    // react hot loader must come before class properties plugin
    "react-hot-loader/babel",
    // class properties plugin must come after decorators
    // if decorators has a 'legacy' attribute, class properties must be loose
    ["@babel/plugin-proposal-class-properties", {"loose" : true}],
    "@babel/plugin-transform-runtime"
  ];

  return {
    presets,
    plugins
  };
};

Из клиентского каталога, который я запускаю в терминале node nightwatch.conf.js ; nightwatch

Вот постоянная ошибка

/Users/myUser/Documents/api/test/factories/index.js:1
(function (exports, require, module, __filename, __dirname) { import bluebird from 'bluebird';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Module._compile (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (module.js:580:10)
    at Object.newLoader [as .js] (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:104:7)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)

Моя интуиция говорит мне, что причина, по которой маркер импорта не распознан, должнаделать с тем, как Babel 7 оценивает компиляцию кода доprocess.cwd().Как вы видите, ошибка исходит от API.Поскольку nightwatch - это пакет в каталоге клиента, Babel не компилирует каталог api (который все еще находится в Babel 6).Тем не менее, я бы хотел избежать рефакторинга всего нашего пакета тестирования клиента, чтобы он не зависел от файлов API.

Я подозреваю, что решение состоит в том, чтобы найти способ для @babel/register скомпилировать API со стороны клиента, но я не знаю, как мне поступить таким образом.

...