【问题标题】:Unexpected token export with TypeScript project - issue with transformIgnorePattern使用 TypeScript 项目意外导出令牌 - transformIgnorePattern 问题
【发布时间】:2020-11-20 16:06:26
【问题描述】:

我有一个带有 Jest 测试的 TypeScript 项目,它工作得很好,使用 ts-jest 作为我的转换器。但是,当我尝试使用似乎是用 TypeScript 编写但作为 ES6 分发的包时,当我的测试运行时遇到“export”关键字时,我遇到了可怕的:“Unexpected token export”错误那个新包。

我明白为什么会这样,但即使在广泛研究了这个问题并看到其他人如何用transformIgnorePatterns 修复它(比如这篇文章comment 和其他很多人)之后,我也无法弄清楚如何解决它,但到目前为止我还没有取得任何进展。

测试运行良好,直到我导入并引用这些问题库之一。只需添加:

import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
...
const x: EnvironmentType = Environment.type;

...然后运行我的测试给我:

/Users/ac/_play/jest-transform-repro/node_modules/@microsoft/sp-core-library/lib/index.js:11
export { default as _BrowserDetection } from './BrowserDetection';
^^^^^^

SyntaxError: Unexpected token export

我创建了一个项目来在这里轻松地解决我的问题:https://github.com/andrewconnell/jest-transform-repro

  1. 克隆https://github.com/andrewconnell/jest-transform-repro
  2. npm 安装
  3. npm 测试

观察一切正常

  1. 打开文件 ./src/webparts/helloWorld/components/Sample/Sample.tsx 并取消注释这两行
  2. npm 测试

观察失败

我尝试将我的transformIgnorePatterns 更新为<rootDir>/../node_modules/(?!(@microsoft/sp-core-library)) 和不同的风格,但这没有帮助。我看过关于更改 .bablerc => babel.config.js 的帖子,但我没有在我的项目中使用 Babel,因为它都是 TypeScript。

一旦我为这个库工作,我知道我需要排除更多......更多......所以理想情况下我想创建一些解决“@microsoft/*”包和不仅仅是上面列出的一个,你可以从上面 repo 中的默认“npm install”中看到,还有很多会给我带来问题。

想法?我很茫然:(

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    这些是我为了在 TS SPFX 项目下工作而进行的更改:

    tsconfig.json

    • 启用"allowJs": true,

    package.json(添加笑话配置):

        "jest": {    
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js",
          "json"
        ],
    
        "testURL": "http://localhost",
        "transform": {
          "^.+\\.(js|ts|tsx)$": "ts-jest"
        },
        "transformIgnorePatterns": [
          "node_modules/(?!(@microsoft/sp-dialog|@microsoft/office-ui-fabric-react-bundle|@microsoft/sp-diagnostics|@microsoft/sp-core-library|@microsoft/sp-http|@microsoft/sp-page-context|@microsoft/sp-dynamic-data|@pnp/sp|@pnp/common|@pnp/odata|@pnp))"
        ],
        "testMatch": [
          "**/src/**/*.test.+(ts|tsx|js)",
          "**/__tests__/**/*.(spec|test).+(tsx|ts|js)?(x)"
        ],
        "moduleNameMapper": {
          "\\.(css|less|scss|sass)$": "identity-obj-proxy",
          "^resx-strings/en-us.json": "<rootDir>/node_modules/@microsoft/sp-core-library/lib/resx-strings/en-us.json"
        },
      }
    

    附加包:

    • "ts-jest": "^24.0.2",
    • "jest": "^26.6.3","jest-junit": "^12.0.0",
    • "@types/jest": "^26.0.15",
    • "identity-obj-proxy": "^3.0.0",

    另一方面,我使用的是react-testing-library,而不是enzyme

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 2018-01-10
      • 2021-10-03
      • 2016-04-27
      • 2021-05-24
      • 2017-12-11
      • 2017-03-05
      • 2017-07-17
      • 1970-01-01
      相关资源
      最近更新 更多