使用REACT从巴别塔迁移到SWC [英] Migrating from Babel to SWC with React

查看:28
本文介绍了使用REACT从巴别塔迁移到SWC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR

如何翻译节点脚本:

"test": "NODE_ENV=test riteway -r @babel/register 'src/**/*.test.js' | tap-nirvana",

使用SWC而不是巴别塔?


上下文

我们最近升级了Next.js版本。Next.js现在支持SWC instead of Babel.

我们项目中Reaction的单元测试是用RITEway编写的。测试命令为:

"test": "NODE_ENV=test riteway -r @babel/register 'src/**/*.test.js' | tap-nirvana",

它首先使用Babel转换文件,否则import语句和JSX将导致错误。

在我们尝试迁移到SWC的过程中,我们在CLI上运气不佳。然而,我们发现了@swc-node/register package。它允许我们将我们的命令转换为:

"test": "riteway -r @swc-node/register src/**/*.test.js | tap-nirvana"

它修复了类似import语句的新语法,并且将运行这样的测试:

import { describe } from 'riteway';

describe('my test', async assert => {
  assert({
    given: 'true',
    should: 'be true',
    actual: true,
    expected: true,
  });
});

但是,像这样的Reaction组件的测试

import { describe } from 'riteway';
import render from 'riteway/render-component';

import Authentication from './user-authentication-component';

describe('user authentication component', async assert => {
  const $ = render(<Authentication />);

  assert({
    given: 'just rendering',
    should: "render 'Authentication'",
    actual: $('*:contains("Authentication")').text(),
    expected: 'Authentication',
  });
});

仍引发以下错误:

$ yarn test
yarn run v1.22.17
$ riteway -r @swc-node/register src/**/*.test.js | tap-nirvana
/Users/user/dev/learning-flow/node_modules/@swc/core/index.js:135
        return bindings.transformSync(isModule ? JSON.stringify(src) : src, isModule, toBuffer(newOptions));
                        ^

Error: error: Expression expected
 
  |
7 |   const $ = render(<Authentication />);
  |                                    ^

error: Expression expected
 
  |
7 |   const $ = render(<Authentication />);
  |                                     ^

error: Unexpected token `)`. Expected this, import, async, function, [ for array literal, { for object literal, @ for decorator, function, class, null, true, false, number, bigint, string, regexp, ` for template literal, (, or an identifier
 
  |
7 |   const $ = render(<Authentication />);
  |                                      ^



Caused by:
    0: failed to process js file
    1: Syntax Error
    at Compiler.transformSync

如何创建该命令以使其与SWC一起运行?

推荐答案

经过一些试验,我发现如果您在每个文件(包括组件和测试)中import React from 'react';并将文件扩展名更改为.jsx(如in the docs所述),它就可以工作。

但是,这并不令人满意,因为我们希望使用React 17's JSX transform feature来避免在每个文件中都导入REACT。此外,我们希望保留所有文件结尾.js

我们尝试了setting .swcrc,到目前为止没有任何成功。

我在此发布此答案,以防找不到配置.swcrc的方法。

这篇关于使用REACT从巴别塔迁移到SWC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆