Coder Social home page Coder Social logo

sukkaw / rollup-plugin-swc Goto Github PK

View Code? Open in Web Editor NEW
141.0 3.0 15.0 660 KB

Use SWC with Rollup to transform / minify ESNext and TypeScript code.

License: MIT License

TypeScript 99.44% JavaScript 0.56%
rollup rollup-plugin swc esnext typescript jsx tsx minifier

rollup-plugin-swc's Introduction

rollup-plugin-swc

SWC is an extensible Rust-based platform for the next generation of fast developer tools. This plugin is designed to replace rollup-plugin-typescript2, @rollup/plugin-typescript, @rollup/plugin-babel and rollup-plugin-terser for you.

New: Building library for React Server Component support is added in 0.9.0! 'use client' and 'use server' directives now are handled properly, without triggering rollup warnings. Start using 'use client' and 'use server' in your library by adding two lines in your rollup.config.js

Since 0.9.1 the support for 'use client' and 'use server' has been separated into a standalone rollup plugin rollup-preserve-directives, the previous preserveUseDirective named export is retained for the backward compatibility.

Comparison

sukkaw/rollup-plugin-swc mentaljam/rollup-plugin-swc nicholasxjy/rollup-plugin-swc2 @rollup/plugin-swc
minify your bundle in one pass1 โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Standalone swcMinify plugin โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Config Intellisense2 โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
Reads your tsconfig.json and jsconfig.json โœ… ๐Ÿ›‘ ๐Ÿ›‘ ๐Ÿ›‘
ESM export โœ… ๐ŸŸก3 ๐Ÿ›‘ โœ…
TypeScript declarations โœ… โœ… โœ… โœ…
Has testing โœ… ๐Ÿ›‘ ๐Ÿ›‘ โœ…

Install

$ npm i @swc/core rollup-plugin-swc3
# If you prefer yarn
# yarn add @swc/core rollup-plugin-swc3
# If you prefer pnpm
# pnpm add @swc/core rollup-plugin-swc3

Usage

// rollup.config.js
import { swc } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc({
      // All options are optional
      include: /\.[mc]?[jt]sx?$/, // default
      exclude: /node_modules/, // default
      tsconfig: 'tsconfig.json', // default
      // tsconfig: false, // You can also prevent `rollup-plugin-swc` from reading tsconfig.json, see below
      // And add your swc configuration here!
      // "filename" will be ignored since it is handled by rollup
      jsc: {}
    }),
  ];
}

If you want autocompletion in your IDE or type check:

import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      // ... There goes the plugin's configuration
    })),
  ];
}

// or
/** @type {import('rollup-plugin-swc3').PluginOptions} */
const swcPluginConfig = {}

exclude

  • Type: string | RegExp | Array<String | RegExp>
  • Default: /node_modules/

A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore.

extensions

  • Type: string[]
  • Default: ['.ts', '.tsx', '.mjs', '.js', '.cjs', '.jsx']

Specifies the files in the build the plugin should operate on. Also, the plugin will search and resolve files for extensions in the order specified for extensionless imports.

include

  • Type: string | RegExp | Array<String | RegExp>
  • Default: /\.[mc]?[jt]sx?$/

A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on.

tsconfig

  • Type: string | false | undefined
  • Default: 'tsconfig.json'

rollup-plugin-swc will read your tsconfig.json or jsconfig.json for default values if your doesn't provide corresponding swc options:

  • The configuration your passed to rollup-plugin-swc will always have the highest priority (higher than tsconfig.json/jsconfig.json).
  • rollup-plugin-swc uses get-tsconfig to find the tsconfig.json/jsconfig.json for the file currently being transpiled.
    • You can also provide a custom filename (E.g. tsconfig.rollup.json, jsconfig.compile.json) to tsconfig option, and rollup-plugin-swc will find and resolve the nearest file with that filename.
    • You can also provide an absolute path (E.g. /path/to/your/tsconfig.json) to tsconfig option, and rollup-plugin-swc will only use the provided path as a single source of truth.
  • You can prevent rollup-plugin-swc from reading tsconfig.json/jsconfig.json by setting tsconfig option to false.
  • jsconfig.json will be ignored if tsconfig.json and jsconfig.json both exist.
  • The extends of tsconfig.json/jsconfig.json is not supported now supported.
  • compilerOptions.target will be passed to swc's jsc.target.
  • compilerOptions.jsxImportSource, compilerOptions.jsxFactory, and compilerOptions.jsxFragmentFactory will be passed to swc's jsc.transform.react.importSource, jsc.transform.react.pragma and jsc.transform.react.pragmaFrag.
  • When compilerOptions.jsx is either react-jsx or react-jsxdev, swc's jsc.transform.react.runtime will be automatic, otherwise it will be classic.
    • compilerOptions.jsx: react-jsxdev will also set swc's jsc.transform.react.development to true.
    • compilerOptions.jsx: preserve will be ignored. swc will always transpile your jsx into javascript code.
  • compilerOptions.baseUrl and compilerOptions.paths will be passed to swc's jsc.baseUrl and jsc.paths directly. They won't affect how rollup resolve your imports. If you have encounted any issue during bundling, please use other plugins to resolve your imports' aliases (e.g., add rollup-plugin-typescript-paths or rollup-plugin-tsconfig-paths before @rollup/plugin-node-resolve).
  • compilerOptions.importHelpers will be passed to swc's jsc.externalHelpers. You will have to have @swc/helpers avaliable in your project when enabled.
  • compilerOptions.experimentalDecorators and compilerOptions.emitDecoratorMetadata will be passed to swc's jsc.parser.decorators and jsc.transform.decoratorMetadata.
  • compilerOptions.esModuleInterop will always be ignored, as swc requires module.type to exist when module.noInterop is given.

Standalone Minify Plugin

If you only want to use swc to minify your bundle:

import { minify } from 'rollup-plugin-swc3'

export default {
  plugins: [
    minify({
      // swc's minify option here
      // mangle: {}
      // compress: {}
    }),
  ],
}

If you want autocompletion in your IDE or type check:

import { minify, defineRollupSwcMinifyOption } from 'rollup-plugin-swc3'

export default {
  plugins: [
    minify(
      defineRollupSwcMinifyOption({
        // swc's minify option here
        // mangle: {}
        // compress: {}
      })
    ),
  ],
}

// or
/** @type {import('@swc/core').JsMinifyOptions} */
const swcMinifyConfig = {}

React Server Component directives ('use client' and 'use server')

Since version 0.9.0, the support for 'use client' and 'use server' has been added:

The support for 'use client' and 'use server' has been separated into a standalone rollup plugin rollup-preserve-directives, maintained by @huozhi and me. The previous preserveUseDirective named export is retained for the backward compatibility.

# npm
npm install -D rollup-preserve-directives
# yarn
yarn add -D rollup-preserve-directives
# pnpm
pnpm add -D rollup-preserve-directives
// rollup.config.js
import { swc } from 'rollup-plugin-swc3';
import preserveDirectives from 'rollup-preserve-directives';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(),
    // And add `preserveDirectives` plugin after the `swc` plugin
    preserveDirectives()
  ];
}

And that is it!

preserveDirectives supports:

  • Merging duplicated directives in the output bundles

    // src/foo.js
    'use sukka';
    'use foxtail';
    
    export const foo = 'foo';
    
    // src/bar.js
    'use sukka';
    export const bar = 'bar';
    
    // src/index.js
    export { foo } from './foo';
    export { bar } from './bar';
    
    // rollup.config.js
    export default {
      input: 'src/index.js',
      output: { file: 'dist/index.js' }
      plugins: [swc(), preserveDirectives()]
    }
    
    // dist/index.js
    'use sukka';
    'use foxtail';
    
    const foo = 'foo';
    const bar = 'bar';
    
    export { foo, bar };
  • When bundle React Client Component and React Server Component separately, mutiple entries will have their own separated and correct directives:

    // src/client.js
    'use client';
    import { useState } from 'react';
    export const Foo = () => { useState('client-only code') };
    
    // src/server.js
    'use server';
    import 'fs';
    export const bar = 'server only code';
    
    // rollup.config.js
    export default {
      // let rollup bundle client and server separately by adding two entries
      input: {
        client: 'src/client.js',
        server: 'src/server.js'
      },
      // output both client bundle and server bundle in the "dist/" directory
      output: { dir: 'dist/', entryFileName: '[name].js' }
      plugins: [swc(), preserveDirectives()]
    }
    
    // dist/client.js
    'use client';
    import { useState } from 'react';
    const Foo = () => { useState('client-only code') };
    export { Foo };
    
    // dist/server.js
    'use server';
    import 'fs';
    const bar = 'server only code';
    export { bar };

Write your Rollup config in TypeScript

You can write your Rollup config file in rollup.config.ts, and use the following command:

rollup --config rollup.config.ts --configPlugin swc3

TypeScript Declaration File

There are serveral ways to generate declaration file:

  • Use tsc with emitDeclarationOnly, the slowest way but you get type checking, it doesn't bundle the .d.ts files.
  • Use rollup-plugin-dts which generates and bundle .d.ts, also does type checking. It is used by this plugin as well.

Use with Non-react JSX

You can either configure it in your tsconfig.json or in your rollup.config.js.

// Vue JSX
import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      jsc: {
        experimental: {
          plugins: [['swc-plugin-vue-jsx', {}]] // npm i swc-plugin-vue-jsx
        }
      }
    })),
  ];
}
// Preact
import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';

export default {
  input: 'xxxx',
  output: {},
  plugins: [
    swc(defineRollupSwcOption({
      jsc: {
        transform:{
          react: {
          pragma: 'h',
          pragmaFrag: 'Fragment'
          // To use preact/jsx-runtime:
          // importSource: 'preact',
          // runtime: 'automatic'
          }
        }
      }
    })),
  ];
}

rollup-plugin-swc ยฉ Sukka, Released under the MIT License.
Inspired by egoist's rollup-plugin-esbuild.
Authored and maintained by Sukka with help from contributors (list).

Personal Website ยท Blog ยท GitHub @SukkaW ยท Telegram Channel @SukkaChannel ยท Mastodon @[email protected] ยท Twitter @isukkaw ยท Keybase @sukka

Footnotes

  1. If minify is called in Rollup's transform phase, every individual module processed will result in a minify call. However, if minify is called in Rollup's renderChunk phase, the minify will only be called once in one whole pass before Rollup generates bundle, results in a faster build. โ†ฉ

  2. Autocompletion and type checking in your IDE โ†ฉ

  3. mentaljam/rollup-plugin-swc has both main and module fields in package.json, but has๐Ÿ›‘exports field. โ†ฉ

rollup-plugin-swc's People

Contributors

citrus327 avatar dashed avatar dbosley avatar g-plane avatar huozhi avatar kdy1 avatar kevinkhill avatar mengdaoshizhongxinyang avatar nonzzz avatar sukkaw avatar systemcluster avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rollup-plugin-swc's Issues

tsconfig paths does not work in rollup config (typescript)

currently i'm using "rollup --config rollup.config.ts --configPlugin swc3" command to bundle my code but when i try to use any tsconfig based alias in rollup.config.ts throws this error

[!] Error: Could not resolve './wizard/src/utils/basic' from rollup.config.ts

wizard is my project name as same as my project directory name. everything is Ok without using the import in rollup.config

wizard
|____src
| |____index.ts
| |____utils
| | |____basic
| | | |____index.ts
| | | |____is.spec.ts
| | | |____is.ts
| | |____logger.ts
|____rollup.config.ts
|____tsconfig.json
|____package.json

rollup.config.ts

...
import {is} from '@utils/basic';
...
export default defineConfig({
  ...
  swc(
      defineRollupSwcOption({
          jsc: {
              parser: {
                  syntax: 'typescript',
                  tsx: true,
                  decorators: true,
                  dynamicImport: true
              },
              baseUrl: './',
              target: 'es5',
              loose: false
          },
          minify: is.mode('production'),
          module: {
              type: 'commonjs',
              strict: false,
              strictMode: true,
              lazy: false,
              noInterop: false
          }
      })
  )
  ...
})

tsconfig.json

{
   "compilerOptions":{
      ...
      "rootDir": ".",
      "baseUrl": ".",
      "paths":{
         "@utils/*": ["src/utils/*"],
         "@/*": ["src/*"],
         "~/*": ["*"]
      }
      ...
   }
}

rollup-plugin-swc-3/dist/index.js

image

outputs

{
  importer: 'absolutepath/wizard/rollup.config.ts',
  path: 'absolutepath/wizard',
  importee: './wizard/src/utils/basic',
  dir: 'absolutepath/wizard',
  resolved: 'absolutepath/wizard/wizard/src/utils/basic'
}

Sourcemaps seem to be broken when using minifcation

When using minification, sourcemap creation seems to be broken, it just creates a source map with content like this:

{"version":3,"file":"ds4.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}

I set sourcemap to true in the output part of the rollup config, and use the following swc plugin configuration

        swc({ minify: true, sourceMaps: true }),

It works perfectly fine when minify is set to false.

Deno

Hi, is there an option to swap the SWC internal with wasm version instead of the default node addon?

Something like

import { rollup } from "npm:rollup"
import { swc } from "npm:rollup-plugin-swc3"

const build = await rollup({
  input: ["main.ts", "lib.mts"],
  plugins: [
    swc({
      wasm: "https://esm.sh/@swc/wasm-web/wasm_bg.wasm"
    }),
  ],
})
await build.write({ dir: "dist", format: "es" })
Just got an error with the default one since Deno doesn't support Node native addons
Error: Failed to convert napi value into rust type `Option<T>`
    at Compiler.<anonymous> (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/@swc/core/1.3.24/index.js:216:33)
    at (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/@swc/core/1.3.24/index.js:34:71)
    at __awaiter (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/@swc/core/1.3.24/index.js:30:12)
    at Compiler.transform (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/@swc/core/1.3.24/index.js:202:16)
    at transform (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/@swc/core/1.3.24/index.js:344:21)
    at Object.transform (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/rollup-plugin-swc3/0.8.0/dist/index.mjs:129:20)
    at (file:///home/wildan/.cache/deno/npm/registry.npmjs.org/rollup/3.9.1/dist/es/shared/rollup.js:23660:40)

Error: `env` and `jsc.target` cannot be used together

I am compiling for a very specific React Native environment which doesn't have all features from ECMAScript 2022 but has some of the most important ones.

This is my config.
image

This is my TSConfig.
image

The issue is from this plugin reading the tsconfig and applying jsc.target automatically, which is impossible to prevent as it is overridden if specified in the plugin parameters or the .swcrc file.

Reading `.swcrc` automatically?

Thank you for great plugin. I've used this for a long time.
I wonder whether this plugin search or take care .swcrc or not.
I've read your source code and found nothing about it, but still I'm not sure.

If it's not supported currently, do you have a plan for partial/full support for .swcrc?

Unable to use ES module configuration file since `0.9.1`

Since 0.9.1, rollup-plugin-swc fails to execute when using an ES module configuration file.

release-branch:build: > tsc && rollup -c
release-branch:build:
release-branch:build: (node:26136) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
release-branch:build: (Use `node --trace-warnings ...` to show where the warning was created)
release-branch:build: [!] RollupError: Node tried to load your configuration file as CommonJS even though it is likely an ES module. To resolve this, change the extension of your configuration to ".mjs", set "type": "module" in your package.json file or pass the "--bundleConfigAsCjs" flag.
release-branch:build:
release-branch:build: Original error: Cannot use import statement outside a module
release-branch:build: https://rollupjs.org/command-line-interface/#bundleconfigascjs
release-branch:build: D:\Development\actions\node_modules\.pnpm\[email protected]_@[email protected][email protected]\node_modules\rollup-swc-preserve-directives\dist\es\index.js:1
release-branch:build: import { extname } from 'path';
release-branch:build: ^^^^^^
release-branch:build:
release-branch:build: SyntaxError: Cannot use import statement outside a module
release-branch:build:     at internalCompileFunction (node:internal/vm:73:18)
release-branch:build:     at wrapSafe (node:internal/modules/cjs/loader:1153:20)
release-branch:build:     at Module._compile (node:internal/modules/cjs/loader:1197:27)
release-branch:build:     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1287:10)
release-branch:build:     at Module.load (node:internal/modules/cjs/loader:1091:32)
release-branch:build:     at Function.Module._load (node:internal/modules/cjs/loader:938:12)
release-branch:build:     at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:165:29)
release-branch:build:     at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
release-branch:build:     at DefaultModuleLoader.import (node:internal/modules/esm/loader:228:24)
release-branch:build:     at importModuleDynamicallyWrapper (node:internal/vm/module:428:15)
release-branch:build:
release-branch:build:
release-branch:build: โ€‰ELIFECYCLEโ€‰ Command failed with exit code 1.
release-branch:build: ERROR: command finished with error: command (D:\Development\actions\actions\release-branch) pnpm run build exited (1)

This seems to be an issue with https://github.com/huozhi/rollup-plugin-swc-preserve-directives, but directly affects users of this package in a patch version update.

Reproducible with https://github.com/Systemcluster/actions, replace "=0.9.0" in configs/rollup-config-workspace/package.json with ^0.9.1 and run npm build.

Treating module as external dependency

Hey,
First of all, awesome work on this and thanks.

I am trying to move my current project from rollup-typescript2 to rollup-plugin-swc3

I treating some of the modules as external dependency, I don't want rollup to bundle them (https://rollupjs.org/troubleshooting/#warning-treating-module-as-external-dependency). This doesn't seem to work.

Minimal project Repos
rollup-typescript2: https://github.com/goldenratio/lerna-rollup2-rtp2-demo
rollup-plugin-swc3: https://github.com/goldenratio/lerna-rollup2-swc-demo

please build project using, npm run build,
Check the generated file, packages/sound/lib/sound.es.js

rtp2 generates, external imports properly

import { add } from '@lerna-demo/utils';

/**
 * PlayFX
 */
var playSFX = function () {
    console.log('playing sound sfx: ', add(4, 5));
};

export { playSFX };
//# sourceMappingURL=sound.es.js.map

But rollup-plugin-swc3, includes the extrernal code. Is it possible to keep it external?

/**
 * @param {number} x
 * @param {number} y
 * @returns {number}
 */ var add = function(x, y) {
    return x + y;
};

/**
 * PlayFX
 */ var playSFX = function() {
    console.log("playing sound sfx: ", add(4, 5));
};

export { playSFX };
//# sourceMappingURL=sound.es.js.map

Compact Output?

Can't you do something like: https://swc.rs/docs/usage/bundling#compact-output for rollup?

I mean to fix the ts paths as well, because at the moment they import them as they are.

With rollup-plugin-swc

'use strict';

var _constants = require("@shared/constants");
mp.events.add('playerReady', function(player) {
    console.log("".concat(player.name, " is ready!"));
    player.customProperty = 1;
    player.customMethod = function() {
        console.log('customMethod called.');
    };
    player.customMethod();
});
console.log(_constants.SHARED_CONSTANTS.HELLO_WORLD);

With rollup-plugin-typescript2

'use strict';

const SHARED_CONSTANTS = {
    HELLO_WORLD: 'HELLO WORLD!'
};

mp.events.add('playerReady', (player) => {
    console.log(`${player.name} is ready!`);
    player.customProperty = 1;
    player.customMethod = () => {
        console.log('customMethod called.');
    };
    player.customMethod();
});
console.log(SHARED_CONSTANTS.HELLO_WORLD);

No sourcemap generated

Here is my rollup config:

import { nodeResolve } from "@rollup/plugin-node-resolve"
import { defineRollupSwcOption, swc } from "rollup-plugin-swc3"

export default {
  input: "src/index.js",
  output: {
    dir: "dist",
    sourcemap: true,
  },
  plugins: [
    nodeResolve(),
    swc(
      defineRollupSwcOption({
        jsc: {
          target: "es2021",
        },
        minify: true,
        sourceMaps: true,
      }),
    ),
  ],
}

Here is the output when I run rollup -c:

src/index.js โ†’ dist...
(!) Broken sourcemap
https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect
Plugins that transform code (such as "swc") should generate accompanying sourcemaps

I tried several configurations and none worked. Please help!

Circular dependency issue

I'm getting a circular dependency warning on eventemitter3, which causes the bundle to fail.

I've reported the issue here, but later found that it only happens if I'm using rollup-plugin-swc3 plugin, and it works fine with @rollup/plugin-typescript and @rollup/plugin-swc. Plain JS also works fine.

On eventemitter3 the index.mjs ESM wrapper imports index.js. The other plugins resolve index.js to index.js however rollup-plugin-swc3 resolves it to index.mjs. Which causes the circular dependency problem.

I was able to workaround it and make it work by changing the order in the extensions configuration. However, I was wondering if this is a bug since only rollup-plugin-swc3 behaves this way.

How to generate .d.ts file?

I have

import { nodeResolve } from '@rollup/plugin-node-resolve';
import { defineRollupSwcOption, swc } from 'rollup-plugin-swc3';

export default {
  input: 'src/index.ts',
  output: {
    dir: 'dist',
    format: 'es',
  },
  plugins: [
    swc(defineRollupSwcOption({
      sourceMaps: true,
      minify: true,
      jsc: {
        paths: {
          '~services': ['./src/services/index'],
          '~services/*': ['./src/services/*'],
          '~/*': ['./src/*'],
        },
        parser: {
          syntax: 'typescript',
          tsx: false,
          dynamicImport: true,
          decorators: true,
          dts: true,
          importAssertions: false,
        },
        transform: {
          legacyDecorator: true,
          decoratorMetadata: true,
        },
        minify: { sourceMap: true },
        target: 'es2018',
        loose: true,
        externalHelpers: false,
        // Requires v1.2.50 or upper and requires target to be es2016 or upper.
        keepClassNames: true,
      },
      
    })),
    nodeResolve(),
  ],
};

And only generates index.js in dist

SWC does not resolve paths from folders

Environment:

// shared.ts
export const SHARED_CONSTANTS = {
	HELLO_WORLD: 'HELLO WORLD!!!'
};
// index.ts
import { SHARED_CONSTANTS } from '@shared/constants';

import './something';
import './my_folder';

console.log(SHARED_CONSTANTS.HELLO_WORLD);
// something.ts
import { SHARED_CONSTANTS } from '@shared/constants';
console.log(SHARED_CONSTANTS.HELLO_WORLD);
// my_folder/index.ts
import { SHARED_CONSTANTS } from '@shared/constants';
console.log(SHARED_CONSTANTS.HELLO_WORLD);
// tsconfig.json
{
	"compilerOptions": {
		"baseUrl": "./",
		"paths": {
			"@shared/*": ["shared/*"],
		}
	}
}
// rollup.config.js
export default {
	// input, output
	plugins: [
		nodeResolvePlugin(),
		jsonPlugin(),
		swc({
			minify: isProduction,
			jsc: {
				parser: {
					syntax: 'typescript'
				},
				baseUrl: '.',
				paths: {
					'@shared/*': [`../shared/*`]
				}
			}
		})
	],
	inlineDynamicImports: true
	// ...
};

Current behaviour:

var constants = require('..\\shared\\constants');

var SHARED_CONSTANTS = {
    HELLO_WORLD: 'HELLO WORLD!!!'
};

console.log('something.ts', SHARED_CONSTANTS.HELLO_WORLD);

console.log('my_folder/index.ts', constants.SHARED_CONSTANTS.HELLO_WORLD);

console.log('index.ts', SHARED_CONSTANTS.HELLO_WORLD);

Expected behaviour:

'use strict';

var SHARED_CONSTANTS = {
    HELLO_WORLD: 'HELLO WORLD!!!'
};

console.log('something.ts', SHARED_CONSTANTS.HELLO_WORLD);
console.log('my_folder/index.ts', SHARED_CONSTANTS.HELLO_WORLD);
console.log('index.ts', SHARED_CONSTANTS.HELLO_WORLD);

I don't know if it's an issue from rollup-plugin-swc3 or SWC itself.

fallbackBindings.transform is not a function

(node:16032) ExperimentalWarning: Importing JSON modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

src/index.ts โ†’ dist/index.js...
[!] (plugin swc) TypeError: fallbackBindings.transform is not a function
src/index.ts
    at Compiler.<anonymous> (/data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/@[email protected]/node_modules/@swc/core/index.js:223:41)
    at Generator.next (<anonymous>)
    at /data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/@[email protected]/node_modules/@swc/core/index.js:34:71
    at new Promise (<anonymous>)
    at __awaiter (/data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/@[email protected]/node_modules/@swc/core/index.js:30:12)
    at Compiler.transform (/data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/@[email protected]/node_modules/@swc/core/index.js:202:16)
    at transform (/data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/@[email protected]/node_modules/@swc/core/index.js:344:21)
    at Object.transform (file:///data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/[email protected]_zz5argbrqg64xved5wkdukot6e/node_modules/rollup-plugin-swc3/dist/index.mjs:129:20)
    at /data/data/com.termux/files/home/ffmpeg-discord/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:24076:40

My rollup.config.js

import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
// import exportDirectoryRollup from 'export-directory/dist/rollup';
import { resolve } from 'path';
import { swc, defineRollupSwcOption } from 'rollup-plugin-swc3';
import swcConfig from './.swcrc.json' assert { type: "json" };

export default {
  input: 'src/index.ts',
  output: {
    file: 'dist/index.js',
    format: 'esm',
  },
  plugins: [
    swc(defineRollupSwcOption(swcConfig)),
    alias({
      entries: {
        $lib: resolve('./src/lib'),
        $core: resolve('./src/core'),
      },
    }),
    // exportDirectoryRollup({}),
    commonjs(),
    nodeResolve({
      browser: true,
      extensions: ['.mjs', '.js', '.ts', '.json'],
    }),
  ],
};

Alias plugin not working with swc plugin.

I might be missing something, but we recently replaced our terser plugin with rollup-plugin-swc and @rollup/plugin-alias stop working.

Here is our configuration

const swcConfig = {
  include: ['src/**/*.ts', '../shared/**/*.ts'],
  exclude: ['src/**/*.test.ts'],
  jsc: {
    parser: {
      syntax: 'typescript',
    },
    target: 'es2015',
    externalHelpers: false,
    minify: { sourceMap: true },
  },
  minify: true,
  sourceMaps: true,
};
const pluginsForNoUAParser = [
  typescript({
    include: ['src/**/*.ts', '../shared/**/*.ts'],
    exclude: ['src/**/*.test.ts'],
  }),
  replace({
    values: replaceConfig[env],
    preventAssignment: true,
  }),
  alias({
    entries: [{ find: 'ua-parser-js', replacement: './src/null.js' }],
  }),
  commonjs(),
  nodeResolve(),
  swc(defineRollupSwcOption(swcConfig)),
];

Any suggestions or ideas would be helpful!

Remove experimental decorators check from SWC config

In current code we are enabling decorators using experimentalDecorators check from tsconfig. This is no longer needed since TypeScript 5 supports decorators stage 3 proposal without a flag. Additionally experimentalDecorators flag enables the legacy decorators and SWC now supports decorators stage 3 proposal as of version 1.3.47 (See: https://swc.rs/docs/configuration/compilation#jsctransformdecoratorversion).

I will be raising a pull request for proposed changes. Let me know your thoughts.

SWC error: `jsc.baseUrl` must be absolute

Problem
With the recent update(issues here and here), swc doesn't accept relative baseUrl anymore. When rollup plugin reads tsconfig.json, it passes baseUrl in whatever format is there, and normally, it is something like . or ./src. It leads to errors:

[!] (plugin swc) Error: failed to handle: base_dir(./) must be absolute. Please ensure that jsc.baseUrl is specified correctly. This cannot be deduced by SWC itself because SWC is a transpiler and it does not try to resolve project details. In other works, SWC does not know which directory should be used as a base directory. It can be deduced if .swcrc is used, but if not, there are many candidates. e.g. the directory containing package.json, or the current working directory. Because of that, the caller (typically the developer of the JavaScript package) should specify it. If you see this error, please report an issue to the package author.

Suggested solution
If tsconfig file found, resolve baseUrl as absolute path (value from its compilerOptions.baseUrl field resolved against absolute path of the given tsconfig file)

SWC packaging doubles the size of the file

My package size was 5.43kb before using rollup-plugin-swc3 and using swc replacement rollup-plugin-typescript2 / @rollup / plugin-babel / rollup-plugin-terser plugin grew to 10.79kb is there a question of variable repeat references?


Version `0.2.0` breaks tsconfig paths

Hey, looks like version 0.2.0 breaks rollup-plugin-tsconfig-paths functionality.

I've made a reproduction code specifically for this issue. LeonardSSH/rollup-plugin-swc-issue

Why do I say it's a version problem?

'Cause downgraded to version 0.1.4, and that works perfectly. I tend to think the problem comes from the commit 290263a.

Current Behavior

PRIVATE โ†’ dist/server.js...

(!) Unresolved dependencies
@shared/constantsts (imported by packages\server\src\index.ts)
created dist/server.js in 71ms

Expected Behavior

PRIVATE โ†’ dist/server.js...
created dist/server.js in 57ms

Maybe it's something to do with the way SWC takes baseUrl and paths?

Locally linked node_modules breaks `tsconfig.json` resolution

The following issue happens when the package where rollup-plugin-swc3 is locally linked.

Error: File './tsconfig.json' not found.
    at Be (/node_modules/get-tsconfig/dist/index.cjs:3:9201)
    at ie (/node_modules/get-tsconfig/dist/index.cjs:3:10245)
    at le (/node_modules/get-tsconfig/dist/index.cjs:3:10975)
    at Object.Le [as getTsconfig] (/node_modules/get-tsconfig/dist/index.cjs:3:11080)
    at p (/node_modules/rollup-plugin-swc3/dist/index.js:1:707)
    at Object.transform (/node_modules/rollup-plugin-swc3/dist/index.js:1:2016)
    at <anonymous> (/node_modules/rollup/dist/shared/rollup.js:1914:40) {
  code: 'PLUGIN_ERROR',
  plugin: 'swc',
  hook: 'transform',
  id: '/random-filename.ts',
  watchFiles: [...]

Relative `baseUrl` path in `tsconfig.json` causes `base_dir(...) must be absolute` error

  • Note that in tsconfig.json, baseUrl can be relative path. #reference
  • To reproduce, please checkout this repository.
    • It contains minimal reproduction files.
    • If you comment out baseUrl in tsconfig.json, npm run build will emit bundle.js
    • If you contain baseUrl in tsconfig.json, npm run build will cause errors like following:
> [email protected] build
> rollup --config rollup.config.js


index.ts โ†’ bundle.js...
thread '<unnamed>' panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/swc_ecma_transforms_module-0.179.5/src/path.rs:122:13:
base_dir(`./src`) must be absolute. Please ensure that `jsc.baseUrl` is specified correctly.

Cannot handle export ts type

Expect behavior

I can export ts type in ts entry file, and in output it could be erased in js asset. And rollup won't complain about resolving

Observed behavior

src/index.ts โ†’ stdout...
(!) Missing exports
https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module
src/index.ts
IConfig is not exported by src/types.ts
1: import { IConfig } from './types';
            ^
2:
3: export { IConfig }
[!] RollupError: "IConfig" is not exported by "src/types.ts", imported by "src/index.ts".
https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module
src/index.ts (1:9)
1: import { IConfig } from './types';
            ^
2:
3: export { IConfig }

Reproduction

https://github.com/beeebox/swc3-export-type-repro

unknown variant `es6`

pnpm --filter memeloop exec rollup --config rollup.config.ts --configPlugin swc3
[!] (plugin swc) Error: unknown variant `es6`, expected one of `es3`, `es5`, `es2015`, `es2016`, `es2017`, `es2018`, `es2019`, `es2020`, `es2021`, `es2022`, `esnext` at line 1 column 375
rollup.config.ts
Error: unknown variant `es6`, expected one of `es3`, `es5`, `es2015`, `es2016`, `es2017`, `es2018`, `es2019`, `es2020`, `es2021`, `es2022`, `esnext` at line 1 column 375

works with --configPlugin typescript

So has to keep @rollup/plugin-typescript for now

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.