Monorepo Jest + Babel 7不在CWD之外转换文件

时间:2019-06-25 01:36:12

标签: javascript node.js jestjs babel babel-register

我只是想开玩笑。我有这样的目录结构:

.
├── api
│   ├── README.md
│   ├── babel.config.js
│   ├── index.js
│   ├── jest.config.js
│   ├── lib
│   │   ├── app.js
│   │   └── db.js
│   ├── package-lock.json
│   ├── package.json
│   └── tests
│       ├── rbac.test.js
│       └── setup
│           ├── env-wrapper.js
│           ├── environment.js
│           └── transformer-wrapper.js
├── babel.config.js
├── common
│   └── models
│       ├── foo.js
│       └── index.js
├── jsconfig.json
├── package-lock.json
└── package.json

通常在根目录中还有其他几个项目,在common/中还有其他子文件夹,但是我已经精简了它以隔离问题。

jest.config.js:

const path = require('path')

require('@babel/register', {
    //needed to transform files outside cwd
    ignore: [/node_modules/i]
})

module.exports = {
    testEnvironment: '<rootDir>/tests/setup/environment.js',
    transform: {
        '^.+\\.[jt]sx?$': '<rootDir>/tests/setup/transformer-wrapper.js',
    }
}

我的环境设置需要api/lib/db.js才能设置数据库进行测试。反过来,api/lib/db.js(从父目录)导入common/models/index.js。 (babel-plugin-module-resolver中的api/babel.config.js处理解析路径)。我已经尝试了@babel/register的几种组合,并包装了环境以及几乎所有我能想到的东西。

相关文件:

tests / setup / environment.js

const NodeEnvironment = require('jest-environment-node')

// This imports DB from lib, which then imports 
// {foo} from 'models' which is in common
// but foo does not get transpiled
const DB = require('../../lib/db').default

....

运行cd api && npm run test时出现此错误:

 FAIL  tests/rbac.test.js
  ● Test suite failed to run

    /Users/jd/Projects/jest-babel-have-mercy-on-my-soul/common/models/index.js:3
    export * from './foo'
    ^^^^^^

    SyntaxError: Unexpected token export

      1 |
    > 2 | import {foo} from 'models'
        | ^
      3 |
      4 | export default {foo}
      5 |

      at Module._compile (../node_modules/pirates/lib/index.js:99:24)
      at Object.<anonymous> (lib/db.js:2:1)

复制步骤:

git clone git@github.com:JonDum/jest-babel-have-mercy-on-my-soul.git fml
cd fml
npm install
cd api
npm install
npm run test

如果有人有任何见解,我将由衷的感谢。几个小时以来,我一直在head撞我的头。

研究

https://www.rondebruin.nl/win/s2/win013.htm https://github.com/facebook/jest/issues/7359 https://github.com/babel/babel/issues/8321 Unable to use Babel 7 with Jest

0 个答案:

没有答案