Exemplos de SWC Rust Compiler

Exemplos de Speedy Web Compiler (SWC) incluindo configuração, plugins, e integração com projetos JavaScript/TypeScript modernos

💻 Configuração Básica de SWC json

🟢 simple ⭐⭐

Configuração completa de SWC para projetos JavaScript/TypeScript com configuração e plugins básicos

⏱️ 15 min 🏷️ swc, configuration, setup
Prerequisites: Node.js, npm/yarn, Basic TypeScript
// 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": process.env.NODE_ENV === "development",
        "refresh": process.env.NODE_ENV === "development",
        "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 };

💻 Exemplos de Integração SWC javascript

🟡 intermediate ⭐⭐⭐

Integração de SWC com frameworks e ferramentas populares incluindo Webpack, Rollup, Jest, e Next.js

⏱️ 30 min 🏷️ swc, integration, tools
Prerequisites: SWC basics, Modern JavaScript tools, Build systems
// 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';

export default [
  {
    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';

export default 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/

💻 Otimização e Plugins Personalizados de SWC typescript

🔴 complex ⭐⭐⭐⭐⭐

Técnicas avançadas de otimização SWC, desenvolvimento de plugins personalizados, e ajuste de performance

⏱️ 50 min 🏷️ swc, plugins, optimization, advanced
Prerequisites: Advanced SWC, Plugin development, Performance optimization
// 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
};