---
title: "TS/TSX"
locale: "zh"
version: "current"
canonicalUrl: "https://farmfe.org/zh/docs/features/script"
publicationStatus: "prerelease"
---

<a id="tstsx"></a>
# TS/TSX


Farm 支持开箱即用地编译` Js/Jsx/Ts/Tsx `，并默认将` Jsx/Tsx `编译为 React。


```tsx
import Button from "./Button";

function ButtonGroup(props: ButtonProps) {
  return (
    <div>
      {props.buttons.map((b) => (
        <Button>{b}</Button>
      ))}
    </div>
  );
}
```


Farm 使用 SWC 来编译脚本，Farm 为脚本编译设置了合理的默认配置。 另外，您可以使用` compilation.script `来配置如何编译脚本文件。 有关详细信息，请参阅 [compilation.script](</zh/docs/config/compilation-options#script>)。


<a id="配置-swc-解析器"></a>
## 配置 Swc 解析器


您可以通过` compilation.script.parser `配置 SWC 解析器。 请参阅 [https://swc.rs/docs/configuration/compilation\#jscparser。](<https://swc.rs/docs/configuration/compilation#jscparser%E3%80%82>)


例如，如果你想启用装饰器，你可以设置` compilation.script.parser.esConfig.decorators `（如果模块是 TS，则设置 tsConfig.decorators）：


```ts
export default {
  compilation: {
    script: {
      // for .js/.jsx files
      esConfig: {
        decorators: true,
      },
      // for .ts/.tsx files
      tsConfig: {
        decorators: true,
      },
    },
  },
};
```


默认情况下，Farm 为` .jsx|.tsx `文件设置` jsx: true `。 其他字段默认为 SWC 的默认值。


<a id="配置目标执行环境"></a>
## 配置目标执行环境


运行项目时使用` compilation.script.target `配置目标环境，Farm 将其默认设置为` ESNext `。


此选项可以与` compilation.presetEnv `一起使用，以针对旧浏览器优雅地降级您的项目。 例如，您可以将 target 设置为 ` ES5 ` 并启用 ` presetEnv `，那么您的项目将完全降级到 ES5。


```ts
export default {
  compilation: {
    script: {
      target: "ES5",
    },
    presetEnv: true,
  },
};
```


有关` presetEnv `的更多信息，请参阅 [Polyfill](</zh/docs/advanced/polyfill>)。


<a id="原生顶层-await"></a>
## 原生顶层 Await


Farm 通过 [` compilation.script.nativeTopLevelAwait `](</zh/docs/config/compilation-options#scriptnativetoplevelawait>) 支持原生顶层 ` await `。启用后，Farm 会保留模块顶层的 ` await ` 而不是将其转换。


```ts
import { defineConfig } from '@farmfe/core';

export default defineConfig({
  compilation: {
    script: {
      nativeTopLevelAwait: true,
    },
  },
});
```



> [!NOTE]
> 备注
> 
> 目标环境必须支持顶层 await（如现代浏览器、Node.js 14.8+）。



<a id="仅类型导入行为"></a>
## 仅类型导入行为


使用 [` compilation.script.importNotUsedAsValues `](</zh/docs/config/compilation-options#scriptimportnotusedasvalues>) 控制仅类型导入的行为，对应 TypeScript 的 ` --importsNotUsedAsValues ` 标志。选项：


- ` remove ` — 删除仅导入类型的 import 语句（默认）
- ` preserve ` — 保留所有 import 语句


<a id="装饰器"></a>
## 装饰器


装饰器默认不启用, 可以通过设置 ` compilation.script.parser.tsConfig.decorators ` 为 ` true ` 来启用装饰器。


```ts
import { defineConfig } from "@farmfe/core";

export default defineConfig({
  compilation: {
    script: {
      parser: {
        tsConfig: {
          // 启用装饰器
          decorators: true,
        },
      },
      // 配置装饰器
      decorators: {
        legacyDecorator: true,
        decoratorMetadata: false,
        decoratorVersion: '2021-12',
        includes: ["src/broken.ts"],
        excludes: ['node_modules/'],
      }
    },
  },
});
```


> Farm 提供了一个装饰器的示例，可以看 [https://github.com/farm-fe/farm/tree/main/examples/decorators](<https://github.com/farm-fe/farm/tree/main/examples/decorators>)


> 默认情况下, Farm 不会转译 ` node_modules ` 下的装饰器, 参考 [compilation.script.decorators.excludes](</zh/docs/config/compilation-options#scriptdecorators>).


<a id="使用-swc-插件"></a>
## 使用 SWC 插件


SWC Plugins 可以直接在 Farm 中使用，例如我们在 Farm 中使用 ` swc-plugin-vue-jsx ` 来编译 Vue JSX。如果需要 Vue SFC 支持，请注册当前的 Rust 插件 ` @farmfe/plugin-vue `：


```ts
import vue from "@farmfe/plugin-vue";

/**
 * @type {import('@farmfe/core').UserConfig}
 */
export default {
  compilation: {
    script: {
      plugins: [
        {
          name: "swc-plugin-vue-jsx",
          options: {
            transformOn: true,
            optimize: true,
          },
          filters: {
            // resolvedPaths: [".+"]
            moduleTypes: ["tsx", "jsx"],
          },
        },
      ],
    },
  },
  plugins: [vue()],
};
```


有关更多详细信息，请参阅[使用插件](</docs/using-plugins#using-swc-plugins>)。


<a id="vite-风格的-importmetaglob"></a>
## Vite 风格的 ` import.meta.glob `


Farm 支持字面量形式的 Vite 风格 ` import.meta.glob `，参考 [glob import](<https://vite.dev/guide/features#glob-import>)。Rust 匹配器以 Vite 8.3.5 的 JavaScript glob 路径为对齐目标，不代表完整兼容所有 picomatch 或原生 Rolldown 行为。


支持 ` eager `、` import `、` query `、` exhaustive `、` caseSensitive `、` base `，并保留旧的 ` as: 'raw' | 'url' `。模式和选项必须为静态字面量；不支持的选项和非法值会产生编译错误，不会静默切换匹配方言。


负模式的排除不受数组中位置影响。默认不包含隐藏文件和 ` node_modules `，` exhaustive: true ` 可在发现文件时包含它们；extglob 关闭。对象键排序后输出，query 仅附加到导入路径，不污染对象键。相对 ` base ` 以 importer 目录为基准，绝对 ` base ` 以项目根目录为基准，返回键相对于该目录。


```ts
const modules = import.meta.glob('./*.js', {
  base: './dir',
  import: 'default',
  query: '?raw',
});
// 键为 './foo.js'，导入路径为 './dir/foo.js?raw'
```


开发模式下，匹配文件的新增和删除会让 importer 重新编译，并通过 HMR 更新 glob 对象；文件事件仍遵循 watcher 的排除配置。源码、许可来源和兼容边界见 [` farmfe_ecosystem_glob `](<https://github.com/farm-fe/farm/tree/main/rust-ecosystem/glob>)。


例如:


```ts
const modules = import.meta.glob("./dir/*.js");
```


将会被编译成以下结果


```ts
// code produced by Farm
const modules = {
  "./dir/foo.js": () => import("./dir/foo.js"),
  "./dir/bar.js": () => import("./dir/bar.js"),
};
```


使用 ` { eager: true } ` 后:


```ts
const modules = import.meta.glob("./dir/*.js", { eager: true });
```


将会被编译成以下结果:


```ts
// code produced by Farm
import * as __glob__0_0 from "./dir/foo.js";
import * as __glob__0_1 from "./dir/bar.js";
const modules = {
  "./dir/foo.js": __glob__0_0,
  "./dir/bar.js": __glob__0_1,
};
```


支持数组形式:


```ts
const modules = import.meta.glob(["./dir/*.js", "./another/*.js"]);
```


支持通过 ` ! ` 排除某些匹配:


```ts
const modules = import.meta.glob(["./dir/*.js", "!**/bar.js"]);
```


```ts
// code produced by Farm
const modules = {
  "./dir/foo.js": () => import("./dir/foo.js"),
};
```



> [!NOTE]
> 备注
> 
> - ` import.meta.glob ` 参数必须全部是字面量，不能使用表达式。
> - ` import.meta.glob ` 在编译时处理和转换，在运行时不存在。
