Skip to content

Commit

Permalink
Merge pull request #2 from 2fd/fix/preserve-ts-packages
Browse files Browse the repository at this point in the history
fix: preserve extension if the import is a package
  • Loading branch information
2fd authored Apr 17, 2024
2 parents a3e816b + f5b0470 commit d2972e1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 10 deletions.
59 changes: 50 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,59 @@
# swc-plugin-allow-importing-ts-extensions

SWC Plugin for allowImportingTsExtensions

## When and Why

If you are using SWC to transpile your TypeScript code, and your target is `es2016` or higher, you can use this plugin to import `.ts` files extensions (instead of `.js`), and it will be transpiled to `.js` files.

## Usage

First, setup your `tsconfig.json` to allow importing `.ts` files extensions.

```json
{
"$schema": "http://json.schemastore.org/swcrc",
"jsc": {
"experimental": {
"plugins": [
["swc-plugin-allow-importing-ts-extensions", {}]
]
}
```json5
// tsconfig.json
{
compilerOptions: {
// ...
noEmit: true,
allowImportingTsExtensions: true,
},
// ...
}
```

Then, add the plugin to your `.swcrc` file.

```json5
// .swcrc
{
$schema: "http://json.schemastore.org/swcrc",
jsc: {
experimental: {
plugins: [["swc-plugin-allow-importing-ts-extensions", {}]],
},
},
}
```

## Options

```json5
// .swcrc
{
// ...
plugins: [
[
"swc-plugin-allow-importing-ts-extensions",
{
preserveImportExtension: true, // default: false
},
],
],
// ...
}
```

| option | type | default | description |
| ------------------------- | --------- | ------- | -------------------------------------------------------- |
| `preserveImportExtension` | `boolean` | `false` | If `true` all imports with extension `.mts` and `.cts` with be map to `.mjs` and `.cjs` respectively, otherwise it will map to `.js` |
4 changes: 3 additions & 1 deletion src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ pub struct Config {
}

fn replace_ts_extension(src: &ast::Str, config: &Config) -> Option<ast::Str> {
if src.value.ends_with(".ts") && !src.value.ends_with(".d.ts") {
if !src.value.starts_with('.') {
return None;
} else if src.value.ends_with(".ts") && !src.value.ends_with(".d.ts") {
if let Some(file) = src.value.strip_suffix(".ts") {
return Some(format!("{}.js", file).into());
}
Expand Down

0 comments on commit d2972e1

Please sign in to comment.