Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHESPTRUFRDEEN

Elysia Tools

Navigation

Build Tools

SWC Rust Compiler Samples

Speedy Web Compiler (SWC) examples including configuration, plugins, and integration with modern JavaScript/TypeScript projects

Samples

Entries inside this sample collection

CodejsonSimple

SWC Basic Configuration

Complete SWC setup for JavaScript/TypeScript projects with basic configuration and plugins

Difficulty

3/10

Estimated time

15 min

Tags

swc, configuration, setup

Prerequisites

Node.js, npm/yarn, Basic TypeScript

json
// SWC Basic Configuration Setup

// 1. Installation
// npm install --save-dev @swc/core @swc/cli
// npm install --save-dev @swc/jest @swc/register (for testing)

// 2. .swcrc - Basic SWC Configuration
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true,
      "dynamicImport": true,
      "importAssertions": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "development": false,
        "refresh": false,
        "pragma": "React.createElement",
        "pragmaFrag": "React.Fragment"
      },
      "decoratorMetadata": true,
      "legacyDecorator": true,
      "useDefineForClassFields": true
    },
    "target": "es2020",
    "loose": false,
    "externalHelpers": false,
    "keepClassNames": false,
    "shorthand": "object",
    "minify": {
      "compress": true,
      "mangle": true
    }
  },
  "module": {
    "type": "es6",
    "strict": true,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  },
  "minify": true,
  "sourceMaps": true,
  "inlineSourcesContent": false,
  "exclude": [
    "node_modules",
    "dist",
    "build",
    "**/*.test.ts",
    "**/*.spec.ts"
  ],
  "env": {
    "production": {
      "minify": true,
      "sourceMaps": false,
      "jsc": {
        "minify": {
          "compress": {
            "drop_console": true,
            "drop_debugger": true,
            "pure_funcs": ["console.log"]
          }
        }
      }
    },
    "development": {
      "minify": false,
      "sourceMaps": true,
      "jsc": {
        "transform": {
          "react": {
            "development": true,
            "refresh": true
          }
        }
      }
    },
    "test": {
      "minify": false,
      "sourceMaps": true,
      "jsc": {
        "transform": {
          "react": {
            "development": true
          }
        }
      }
    }
  }
}

// 3. .swcrc for React with TypeScript
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "development": true,
        "refresh": true,
        "importSource": "@emotion/react"
      }
    },
    "target": "es2020",
    "externalHelpers": false
  },
  "module": {
    "type": "es6"
  },
  "sourceMaps": true
}

// 4. .swcrc for Node.js Backend
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    },
    "target": "es2022",
    "externalHelpers": true
  },
  "module": {
    "type": "commonjs"
  },
  "sourceMaps": true,
  "exclude": ["node_modules"]
}

// 5. package.json scripts using SWC
{
  "name": "my-swc-project",
  "version": "1.0.0",
  "scripts": {
    "build": "swc src --out-dir dist",
    "build:watch": "swc src --out-dir dist --watch",
    "build:minify": "NODE_ENV=production swc src --out-dir dist",
    "start": "node dist/index.js",
    "dev": "swc src --out-dir dist --watch & nodemon dist/index.js",
    "clean": "rm -rf dist",
    "type-check": "tsc --noEmit"
  },
  "devDependencies": {
    "@swc/cli": "^0.1.62",
    "@swc/core": "^1.4.0",
    "@types/node": "^20.8.0",
    "typescript": "^5.2.0",
    "nodemon": "^3.0.0"
  },
  "dependencies": {
    "@swc/helpers": "^0.5.0"
  }
}

// 6. tsconfig.json (companion to SWC)
{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["ES2020"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "declaration": true,
    "declarationMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"],
      "@/utils/*": ["utils/*"],
      "@/types/*": ["types/*"]
    },
    "jsx": "react-jsx",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "build",
    "**/*.test.ts",
    "**/*.spec.ts"
  ]
}

// 7. Command-line usage examples
/*
# Basic compilation
swc src --out-dir dist

# Watch mode
swc src --out-dir dist --watch

# Compile specific file
swc src/index.ts --out-file dist/index.js

# Minify output
swc src --out-dir dist --minify

# Disable source maps
swc src --out-dir dist --no-sourcemap

# Copy files (non-JS/TS)
swc src --out-dir dist --copy-files

# Ignore files
swc src --out-dir dist --ignore "src/**/*.test.ts,src/**/*.spec.ts"

# Use custom config
swc src --out-dir dist --config-file .swcrc.prod

# Verbose output
swc src --out-dir dist --verbose
*/

// 8. Environment variables for SWC
/*
SWC_SOURCEMAP - Enable/disable source maps
SWC_MINIFY - Enable/disable minification
SWC_TARGET - Compilation target
SWC_MODULE - Module type (es6, commonjs)
SWC_CONFIG_PATH - Path to config file
*/

// 9. Basic source file examples

// src/utils.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function multiply(a: number, b: number): number {
  return a * b;
}

export const PI = 3.14159;

// src/types/index.ts
export interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
}

// src/index.ts
import { add, multiply, PI } from './utils';
import { User, ApiResponse } from './types';

class Calculator {
  private result: number = 0;

  add(value: number): this {
    this.result = add(this.result, value);
    return this;
  }

  multiply(value: number): this {
    this.result = multiply(this.result, value);
    return this;
  }

  getResult(): number {
    return this.result;
  }

  reset(): void {
    this.result = 0;
  }
}

const calc = new Calculator();
const result = calc.add(5).multiply(2).getResult();
console.log('Result:', result);
console.log('PI:', PI);

export { Calculator };
CodejavascriptIntermediate

SWC Integration Examples

Integration of SWC with popular frameworks and tools including Webpack, Rollup, Jest, and Next.js

Difficulty

6/10

Estimated time

30 min

Tags

swc, integration, tools

Prerequisites

SWC basics, Modern JavaScript tools, Build systems

javascript
// SWC Integration Examples with Popular Tools

// 1. Webpack Integration (webpack.config.js)
const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: {
          loader: 'swc-loader',
          options: {
            jsc: {
              parser: {
                syntax: 'typescript',
              },
              target: 'es2020',
            },
            module: {
              type: 'commonjs',
            },
          },
        },
        exclude: /node_modules/,
      },
      {
        test: /\.tsx$/,
        use: {
          loader: 'swc-loader',
          options: {
            jsc: {
              parser: {
                syntax: 'typescript',
                tsx: true,
              },
              transform: {
                react: {
                  runtime: 'automatic',
                },
              },
              target: 'es2020',
            },
            module: {
              type: 'commonjs',
            },
          },
        },
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
  },
};

// 2. Rollup Integration (rollup.config.js)
import swc from '@rollup/plugin-swc';
import typescript from '@rollup/plugin-typescript';

const rollupConfig = [
  {
    input: 'src/index.ts',
    output: [
      {
        file: 'dist/index.js',
        format: 'cjs',
        sourcemap: true,
      },
      {
        file: 'dist/index.esm.js',
        format: 'esm',
        sourcemap: true,
      },
    ],
    plugins: [
      swc({
        jsc: {
          parser: {
            syntax: 'typescript',
          },
          target: 'es2020',
          transform: {
            react: {
              runtime: 'automatic',
            },
          },
        },
        module: {
          type: 'es6',
        },
        exclude: /node_modules/,
      }),
    ],
    external: ['react', 'react-dom'],
  },
];

// 3. Jest Integration (jest.config.js)
module.exports = {
  roots: ['<rootDir>/src'],
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
  },
  transform: {
    '^.+\\.(ts|tsx)$': ['@swc/jest', {
      jsc: {
        parser: {
          syntax: 'typescript',
          tsx: true,
          decorators: true,
        },
        transform: {
          react: {
            runtime: 'automatic',
            development: true,
          },
        },
        target: 'es2020',
      },
    }],
  },
  collectCoverageFrom: [
    'src/**/*.{ts,tsx}',
    '!src/**/*.d.ts',
    '!src/test/**/*',
    '!src/**/*.stories.tsx',
  ],
  coverageReporters: ['text', 'lcov', 'html'],
};

// 4. Next.js Integration (next.config.js)
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    swcMinify: true, // Enable SWC minification
  },
  compiler: {
    removeConsole: process.env.NODE_ENV === 'production',
  },
  webpack(config, { isServer }) {
    // Use SWC for TypeScript files
    config.module.rules.unshift({
      test: /\\.(ts|tsx)$/,
      use: {
        loader: 'swc-loader',
        options: {
          jsc: {
            parser: {
              syntax: 'typescript',
              tsx: true,
              decorators: true,
              dynamicImport: true,
            },
            transform: {
              react: {
                runtime: 'automatic',
              },
            },
            target: 'es2020',
          },
          module: {
            type: isServer ? 'commonjs' : 'es6',
          },
        },
      },
      exclude: /node_modules/,
    });

    return config;
  },
};

module.exports = nextConfig;

// 5. Vite Integration (vite.config.js)
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

const viteConfig = defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
      // Use SWC for Fast Refresh
      fastRefresh: true,
    }),
  ],
  esbuild: false, // Disable esbuild to use SWC
  optimizeDeps: {
    // Exclude dependencies that should be processed by SWC
    exclude: ['@emotion/react', '@emotion/styled'],
  },
  server: {
    fs: {
      // Allow serving files from one level up
      allow: ['..'],
    },
  },
});

// 6. Gulp Integration (gulpfile.js)
const { src, dest, watch, series, parallel } = require('gulp');
const swc = require('gulp-swc');

function compileScripts() {
  return src('src/**/*.{ts,tsx}')
    .pipe(swc({
      jsc: {
        parser: {
          syntax: 'typescript',
          tsx: true,
        },
        target: 'es2020',
      },
      module: {
        type: 'commonjs',
      },
    }))
    .pipe(dest('dist'));
}

function watchFiles() {
  watch('src/**/*.{ts,tsx}', compileScripts);
}

exports.build = compileScripts;
exports.watch = watchFiles;
exports.default = series(compileScripts);

// 7. Custom SWC Plugin Example
// plugins/my-swc-plugin.js
module.exports = function () {
  return {
    visitor: {
      // Transform console.log calls in production
      CallExpression(path) {
        if (
          path.node.callee.type === 'MemberExpression' &&
          path.node.callee.object.type === 'Identifier' &&
          path.node.callee.object.name === 'console'
        ) {
          // Remove or transform console calls
          path.remove();
        }
      },

      // Add version comment to function declarations
      FunctionDeclaration(path) {
        const leadingComments = path.node.leadingComments || [];
        leadingComments.push({
          type: 'CommentLine',
          value: ' Generated by SWC ',
        });
        path.node.leadingComments = leadingComments;
      },
    },
  };
};

// 8. Advanced SWC Configuration with Custom Plugins
// .swcrc
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "development": false,
        "refresh": false
      },
      "optimizer": {
        "globals": {
          "vars": {
            "process.env.NODE_ENV": "production"
          }
        }
      }
    },
    "target": "es2020",
    "experimental": {
      "plugins": [
        ["./plugins/my-swc-plugin.js", {}]
      ]
    },
    "loose": false,
    "externalHelpers": true
  },
  "module": {
    "type": "es6",
    "strict": true
  },
  "minify": true,
  "sourceMaps": true,
  "env": {
    "production": {
      "minify": true,
      "jsc": {
        "minify": {
          "compress": {
            "drop_console": true,
            "drop_debugger": true,
            "pure_funcs": ["console.log", "console.info"],
            "passes": 2
          },
          "mangle": {
            "safari10": true
          }
        }
      }
    }
  }
}

// 9. Docker Integration (Dockerfile)
FROM node:20-alpine

# Install pnpm
RUN npm install -g pnpm

WORKDIR /app

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install dependencies
RUN pnpm install --frozen-lockfile

# Copy source code
COPY .swcrc ./
COPY tsconfig.json ./
COPY src ./src

# Build with SWC
RUN pnpm build

# Production stage
FROM node:20-alpine

WORKDIR /app

# Copy built application
COPY --from=0 /app/dist ./dist
COPY --from=0 /app/node_modules ./node_modules
COPY --from=0 /app/package.json ./

EXPOSE 3000

CMD ["node", "dist/index.js"]

// 10. CI/CD Integration (GitHub Actions)
# .github/workflows/build.yml
name: Build and Test

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Type check
        run: npm run type-check

      - name: Build with SWC
        run: npm run build

      - name: Run tests
        run: npm test

      - name: Upload build artifacts
        uses: actions/upload-artifact@v3
        with:
          name: build
          path: dist/
CodetypescriptComplex

SWC Optimization and Custom Plugins

Advanced SWC optimization techniques, custom plugin development, and performance tuning

Difficulty

9/10

Estimated time

50 min

Tags

swc, plugins, optimization, advanced

Prerequisites

Advanced SWC, Plugin development, Performance optimization

typescript
// SWC Advanced Optimization and Custom Plugins

// 1. Performance-Optimized SWC Configuration
// .swcrc.performance
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true,
      "importAssertions": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "development": false,
        "refresh": false,
        "importSource": "@emotion/react"
      },
      "optimizer": {
        "globals": {
          "vars": {
            "process.env.NODE_ENV": "production",
            "process.env.APP_VERSION": "\"1.0.0\""
          }
        }
      }
    },
    "target": "es2022",
    "externalHelpers": true,
    "loose": false,
    "keepClassNames": false,
    "shorthand": "object",
    "assumptions": {
      "noDocumentAll": true,
      "noIterator": true,
      "noIsNan": true,
      "objectRestNoSymbols": true,
      "pureGetters": true,
      "setPublicClassFields": true,
      "skipForOfIteratorClosing": true
    }
  },
  "module": {
    "type": "es6",
    "strict": true,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  },
  "minify": {
    "compress": {
      "drop_console": true,
      "drop_debugger": true,
      "passes": 2,
      "dead_code": true,
      "evaluate": true,
      "hoist_funs": true,
      "hoist_vars": true,
      "inline": 2,
      "join_vars": true,
      "keep_fargs": false,
      "keep_fnames": false,
      "reduce_funcs": true,
      "reduce_vars": true,
      "side_effects": true,
      "switches": true,
      "toplevel": true,
      "typeofs": false,
      "unsafe_comps": true,
      "unsafe_Function": true,
      "unsafe_math": true,
      "unsafe_proto": true,
      "unsafe_regexp": false,
      "unsafe_undefined": true
    },
    "mangle": {
      "safari10": true,
      "properties": {
        "regex": "^_",
        "reserved": []
      },
      "topretain": ["init", "config", "handler"],
      "keep_fnames": false,
      "keep_classnames": false
    }
  },
  "sourceMaps": false,
  "inlineSourcesContent": false
}

// 2. Custom Plugin: Bundle Size Analyzer
// plugins/bundle-analyzer-plugin.ts
import { Visitor } from '@swc/core/Visitor';
import { Module } from '@swc/core';

interface BundleStats {
  functions: number;
  classes: number;
  imports: number;
  exports: number;
  variables: number;
}

class BundleAnalyzerPlugin extends Visitor {
  private stats: BundleStats = {
    functions: 0,
    classes: 0,
    imports: 0,
    exports: 0,
    variables: 0
  };

  visitFunction(path: any) {
    this.stats.functions++;
    return super.visitFunction(path);
  }

  visitClass(path: any) {
    this.stats.classes++;
    return super.visitClass(path);
  }

  visitImportDeclaration(path: any) {
    this.stats.imports++;
    return super.visitImportDeclaration(path);
  }

  visitExportDeclaration(path: any) {
    this.stats.exports++;
    return super.visitExportDeclaration(path);
  }

  visitVariableDeclaration(path: any) {
    this.stats.variables++;
    return super.visitVariableDeclaration(path);
  }

  getStats(): BundleStats {
    return this.stats;
  }
}

export function bundleAnalyzer() {
  return new BundleAnalyzerPlugin();
}

// 3. Custom Plugin: Import Optimizer
// plugins/import-optimizer-plugin.ts
import { Visitor } from '@swc/core/Visitor';

class ImportOptimizerPlugin extends Visitor {
  private static readonly LodashMethods = new Set([
    'map', 'filter', 'reduce', 'forEach', 'find', 'some', 'every', 'flatMap'
  ]);

  visitImportDeclaration(path: any) {
    const { node } = path;

    if (
      node.source.value === 'lodash' &&
      node.specifiers?.some((spec: any) =>
        spec.type === 'ImportDefaultSpecifier'
      )
    ) {
      // Convert `import _ from 'lodash'` to named imports
      console.warn('Consider using named imports for lodash:', node);
    }

    // Convert namespace imports to named imports where possible
    node.specifiers?.forEach((spec: any) => {
      if (spec.type === 'ImportNamespaceSpecifier') {
        console.warn('Namespace import detected:', spec.local.name);
      }
    });

    return super.visitImportDeclaration(path);
  }
}

export function importOptimizer() {
  return new ImportOptimizerPlugin();
}

// 4. Custom Plugin: React Performance Optimizer
// plugins/react-optimizer-plugin.ts
import { Visitor } from '@swc/core/Visitor';

class ReactOptimizerPlugin extends Visitor {
  visitArrowFunctionExpression(path: any) {
    const { node } = path;

    // Suggest useCallback for arrow functions in React components
    if (this.isInsideReactComponent(path)) {
      console.log('Consider wrapping arrow function in useCallback:', node);
    }

    return super.visitArrowFunctionExpression(path);
  }

  visitFunctionDeclaration(path: any) {
    const { node } = path;

    // Suggest useMemo for expensive computations
    if (this.isExpensiveFunction(node)) {
      console.log('Consider wrapping function in useMemo:', node);
    }

    return super.visitFunctionDeclaration(path);
  }

  visitCallExpression(path: any) {
    const { node } = path;

    // Optimize React.createElement calls
    if (
      node.callee.type === 'MemberExpression' &&
      node.callee.object.name === 'React' &&
      node.callee.property.name === 'createElement'
    ) {
      // Suggest JSX usage over createElement
      console.log('Consider using JSX instead of React.createElement:', node);
    }

    return super.visitCallExpression(path);
  }

  private isInsideReactComponent(path: any): boolean {
    // Check if the current path is inside a React component
    let current = path;
    while (current.parentPath) {
      const parent = current.parentPath.node;
      if (
        parent.type === 'FunctionDeclaration' ||
        parent.type === 'ArrowFunctionExpression'
      ) {
        // Check if it returns JSX
        if (this.returnsJSX(parent)) {
          return true;
        }
      }
      current = current.parentPath;
    }
    return false;
  }

  private returnsJSX(node: any): boolean {
    // Simplified check - in real implementation, this would be more sophisticated
    return node.body?.type?.includes('JSX') || false;
  }

  private isExpensiveFunction(node: any): boolean {
    // Heuristic to detect expensive computations
    const expensivePatterns = ['map', 'filter', 'reduce', 'forEach'];
    const functionBody = JSON.stringify(node);
    return expensivePatterns.some(pattern =>
      functionBody.includes(pattern) && functionBody.length > 100
    );
  }
}

export function reactOptimizer() {
  return new ReactOptimizerPlugin();
}

// 5. Custom Plugin: Internationalization Extractor
// plugins/i18n-extractor-plugin.ts
import { Visitor } from '@swc/core/Visitor';
import * as fs from 'fs';
import * as path from 'path';

interface TranslationKey {
  key: string;
  file: string;
  line: number;
  namespace?: string;
}

class I18nExtractorPlugin extends Visitor {
  private translationKeys: TranslationKey[] = [];
  private currentFile: string = '';

  visitCallExpression(path: any) {
    const { node, parent } = path;

    // Extract translation keys from t('key') calls
    if (
      node.callee.type === 'Identifier' &&
      node.callee.name === 't' &&
      node.arguments.length > 0
    ) {
      const firstArg = node.arguments[0];

      if (firstArg.type === 'StringLiteral') {
        this.addTranslationKey({
          key: firstArg.value,
          file: this.currentFile,
          line: node.loc?.start.line || 0
        });
      }
    }

    // Extract from useTranslation('namespace') calls
    if (
      node.callee.type === 'Identifier' &&
      node.callee.name === 'useTranslation' &&
      node.arguments.length > 0
    ) {
      const firstArg = node.arguments[0];

      if (firstArg.type === 'StringLiteral') {
        // Store namespace for subsequent t() calls in this scope
        console.log('Found i18n namespace:', firstArg.value);
      }
    }

    return super.visitCallExpression(path);
  }

  private addTranslationKey(key: Omit<TranslationKey, 'file' | 'line'>) {
    this.translationKeys.push({
      ...key,
      file: this.currentFile,
      line: 0 // Would need proper line tracking in real implementation
    });
  }

  setCurrentFile(filePath: string) {
    this.currentFile = filePath;
  }

  getTranslationKeys(): TranslationKey[] {
    return this.translationKeys;
  }

  exportTranslationKeys(outputPath: string) {
    const uniqueKeys = Array.from(
      new Set(this.translationKeys.map(k => k.key))
    );

    const translations: Record<string, string> = {};
    uniqueKeys.forEach(key => {
      translations[key] = ''; // Empty string for translation
    });

    fs.writeFileSync(outputPath, JSON.stringify(translations, null, 2));
  }
}

// Usage example
const i18nPlugin = new I18nExtractorPlugin();
i18nPlugin.setCurrentFile('src/components/MyComponent.tsx');

// 6. Advanced SWC Configuration with Plugins
// .swcrc.advanced
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "development": false,
        "refresh": false
      }
    },
    "experimental": {
      "plugins": [
        ["./plugins/react-optimizer-plugin.ts", {}],
        ["./plugins/import-optimizer-plugin.ts", {}],
        ["./plugins/bundle-analyzer-plugin.ts", {}]
      ]
    },
    "target": "es2022",
    "externalHelpers": true
  },
  "module": {
    "type": "es6"
  },
  "minify": true
}

// 7. Performance Benchmarking Script
// scripts/benchmark-swc.js
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

async function runSWC(options = {}) {
  const startTime = process.hrtime.bigint();

  const swcProcess = spawn('npx', ['swc', 'src', '--out-dir', 'dist', ...options.args], {
    stdio: 'pipe'
  });

  return new Promise((resolve, reject) => {
    let stdout = '';
    let stderr = '';

    swcProcess.stdout.on('data', (data) => {
      stdout += data.toString();
    });

    swcProcess.stderr.on('data', (data) => {
      stderr += data.toString();
    });

    swcProcess.on('close', (code) => {
      const endTime = process.hrtime.bigint();
      const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds

      resolve({
        code,
        duration,
        stdout,
        stderr,
        outputSize: getDirectorySize('dist')
      });
    });

    swcProcess.on('error', reject);
  });
}

function getDirectorySize(dirPath) {
  let totalSize = 0;

  try {
    const files = fs.readdirSync(dirPath);

    files.forEach(file => {
      const filePath = path.join(dirPath, file);
      const stats = fs.statSync(filePath);

      if (stats.isDirectory()) {
        totalSize += getDirectorySize(filePath);
      } else {
        totalSize += stats.size;
      }
    });
  } catch (error) {
    // Directory doesn't exist
  }

  return totalSize;
}

async function runBenchmarks() {
  const configs = [
    { name: 'Basic', args: [] },
    { name: 'Minified', args: ['--minify'] },
    { name: 'No Source Maps', args: ['--no-sourcemap'] },
    { name: 'Production', args: ['--minify', '--no-sourcemap'] }
  ];

  console.log('SWC Performance Benchmark\n');

  for (const config of configs) {
    console.log(`Testing configuration: ${config.name}`);

    // Clean dist directory
    if (fs.existsSync('dist')) {
      fs.rmSync('dist', { recursive: true });
    }

    const result = await runSWC(config);

    console.log(`  Duration: ${result.duration.toFixed(2)}ms`);
    console.log(`  Exit code: ${result.code}`);
    console.log(`  Output size: ${(result.outputSize / 1024).toFixed(2)} KB`);
    console.log();
  }
}

runBenchmarks().catch(console.error);

// 8. SWC Plugin Development Template
// plugins/template-plugin.ts
import { Visitor } from '@swc/core/Visitor';
import { Module } from '@swc/core';

interface PluginOptions {
  option1?: string;
  option2?: boolean;
  customTransform?: (node: any) => any;
}

class TemplatePlugin extends Visitor {
  private options: PluginOptions;

  constructor(options: PluginOptions = {}) {
    super();
    this.options = options;
  }

  visitProgram(path: any) {
    // Called for each module/program
    console.log('Processing file:', path.hub.file.filename);
    return super.visitProgram(path);
  }

  visitFunction(path: any) {
    // Called for each function declaration/expression
    if (this.options.option2) {
      console.log('Found function:', path.node.id?.name);
    }

    return super.visitFunction(path);
  }

  visitIdentifier(path: any) {
    // Called for each identifier
    if (path.node.name === this.options.option1) {
      console.log('Found target identifier:', path.node.name);
    }

    return super.visitIdentifier(path);
  }

  // Add more visitor methods as needed
  visitClassDeclaration(path: any) {
    return super.visitClassDeclaration(path);
  }

  visitCallExpression(path: any) {
    // Apply custom transform if provided
    if (this.options.customTransform) {
      const transformed = this.options.customTransform(path.node);
      if (transformed) {
        path.replaceWith(transformed);
      }
    }

    return super.visitCallExpression(path);
  }
}

export function createTemplatePlugin(options: PluginOptions = {}) {
  return new TemplatePlugin(options);
}

// Export individual plugin creators
export {
  bundleAnalyzer,
  importOptimizer,
  reactOptimizer
};

Tools

Tools frequently paired with this sample

Related

Related sample collections

Tool usage guide

Sample-focused context for search and workflow understanding

Title

SWC Rust Compiler Samples

Description

Speedy Web Compiler (SWC) examples including configuration, plugins, and integration with modern JavaScript/TypeScript projects

Overview

Speedy Web Compiler (SWC) examples including configuration, plugins, and integration with modern JavaScript/TypeScript projects

When to use

  • Use this sample set when you want reference inputs for SWC Rust Compiler Samples.
  • Use it to preview output formats and compare related sample variants.

How it works

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

Use cases

  • SWC Basic Configuration
  • SWC Integration Examples
  • SWC Optimization and Custom Plugins

FAQ

What is included in SWC Rust Compiler Samples?

This page includes curated sample entries, related tools, and neighboring sample collections for SWC Rust Compiler Samples.

Home
Tools3197
Samples593
Visualizations461
Viewers103
Hubs229
Tags333
Images, Audio & Video655

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance644

Calculators, numerics, date logic, statistics, and finance tools

Design & Color296

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

UI Screenshot Structure Review and Development Handoff
Piano Sketch Creation, MIDI Review and Listening Demo Handoff
Retro Game Texture Review and Asset Handoff
Screenshot-Based Procedure Guide Review and Handoff
Responsive Page Change Review and Evidence Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Development

Data URI Generator

Convert files into Data URIs (Base64 or percent-encoded) for inlining images, fonts, and assets directly into HTML, CSS, or Markdown

AI Tools

Receipt & Invoice OCR Recognition

Extract key information from receipt/invoice images and convert to custom JSON format using AI vision models

AI Tools

AI ID Card OCR Recognition

Extract key information from ID card images and convert to JSON format using AI vision models for free

Design

Image Palette to Design Tokens

Extract a dominant color palette from an image (k-means clustering), then export it as CSS variables, SCSS variables, a Tailwind config, or JSON design tokens — with named colors and an auto-generated shade scale for each

Document Tools

PDF Invoice Generator

Generate a branded invoice PDF from structured line items

AI Tools

UI Screenshot to Structured JSON

Turn a screenshot into an editable visual layout tree, component inventory and coding handoff.

Media

Convert ICO to WebP

Convert ICO icon files to WebP format with modern compression and transparency support

Media

Batch Image Crop

Batch crop multiple images to specific dimensions or aspect ratios with custom positioning. Returns cropped images as a ZIP download.

Monitoring

Grafana Advanced Application Samples

Comprehensive Grafana samples covering advanced dashboard design, alerting configurations, data source integrations, and plugin development

Developer Tools

Rome JavaScript Toolchain Samples

Rome JavaScript toolchain examples including configuration, linting, formatting, bundling, and project management

Build Tools

Webpack Configuration Samples

Webpack configuration examples including basic setup, optimization, loaders, plugins, and modern webpack patterns

Document

PDF Samples

Generated PDF samples from tools dated 2026-02-01 to 2026-02-10

Python

Web Image Processing Python Samples

Web Python image processing examples using PIL/Pillow including reading, saving, resizing, and format conversion

Rust

Web Image Processing Rust Samples

Web Rust image processing examples including image read/save, scaling, and format conversion