CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-styled-jsx

Full CSS support for JSX without compromises, providing scoped component-friendly CSS with server-side rendering support

Pending
Overview
Eval results
Files

build-integration.mddocs/

Build Integration

Babel plugin and webpack loader for transforming styled-jsx syntax and processing external CSS files.

Capabilities

Babel Plugin

The core Babel plugin that transforms styled-jsx tagged template literals into optimized runtime code.

/**
 * Babel plugin that transforms styled-jsx tagged templates
 * @param options - Plugin configuration options
 * @returns Babel plugin function
 */
module.exports = function styledJsxBabelPlugin(options?: {
  /** Use CSSOM injection for optimized performance (default: false) */
  optimizeForSpeed?: boolean;
  /** Generate source maps for debugging (default: false) */  
  sourceMaps?: boolean;
  /** Custom path to style module (default: 'styled-jsx/style') */
  styleModule?: string;
  /** Enable automatic vendor prefixing (default: true) */
  vendorPrefixes?: boolean;
  /** CSS preprocessing plugins array */
  plugins?: Array<any>;
}): any;

Basic Setup:

{
  "plugins": ["styled-jsx/babel"]
}

Advanced Configuration:

{
  "plugins": [
    [
      "styled-jsx/babel", 
      {
        "optimizeForSpeed": true,
        "sourceMaps": false,
        "vendorPrefixes": true,
        "plugins": ["styled-jsx-plugin-postcss"]
      }
    ]
  ]
}

Usage Examples:

// .babelrc.js
module.exports = {
  presets: ['@babel/preset-react'],
  plugins: [
    [
      'styled-jsx/babel',
      {
        optimizeForSpeed: process.env.NODE_ENV === 'production',
        sourceMaps: process.env.NODE_ENV === 'development',
        vendorPrefixes: true
      }
    ]
  ]
};

// babel.config.js (for monorepos)
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['styled-jsx/babel', {
      // Development settings
      optimizeForSpeed: false,
      sourceMaps: true,
      vendorPrefixes: true
    }]
  ],
  env: {
    production: {
      plugins: [
        ['styled-jsx/babel', {
          // Production optimizations
          optimizeForSpeed: true,
          sourceMaps: false,
          vendorPrefixes: true
        }]
      ]
    }
  }
};

Webpack Loader

Webpack loader configuration for processing external CSS files with styled-jsx.

/**
 * Webpack loader configuration object
 * Contains path to the webpack loader module
 */
module.exports = {
  /** Path to webpack loader module */
  loader: string;
}

Basic Webpack Setup:

// webpack.config.js
const styledJsxWebpack = require('styled-jsx/webpack');

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'babel-loader',
          styledJsxWebpack.loader
        ]
      }
    ]
  }
};

Advanced Webpack Configuration:

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

module.exports = {
  module: {
    rules: [
      // Handle .jsx and .js files
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react'],
            plugins: [
              ['styled-jsx/babel', {
                optimizeForSpeed: process.env.NODE_ENV === 'production'
              }]
            ]
          }
        }
      },
      // Handle external CSS files with styled-jsx
      {
        test: /\.css$/,
        include: path.resolve(__dirname, 'src/styles'),
        use: [
          'babel-loader',
          {
            loader: require.resolve('styled-jsx/webpack'),
            options: {
              type: 'scoped' // or 'global', 'resolve'
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx', '.css']
  }
};

CSS File Processing

Using external CSS files with styled-jsx webpack loader.

CSS File (styles/button.css):

.button {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.primary {
  background: #007bff;
  color: white;
}

.secondary {
  background: #6c757d;
  color: white;
}

Component Usage:

import buttonStyles from './styles/button.css';

function Button({ variant = 'primary', children, ...props }) {
  return (
    <div>
      <button className={`button ${variant}`} {...props}>
        {children}
      </button>
      {buttonStyles}
    </div>
  );
}

Next.js Integration

styled-jsx is built into Next.js and requires no additional configuration.

// Next.js includes styled-jsx by default
// No babel configuration needed
<style jsx>{`/* styles */`}</style>
<style jsx global>{`/* global styles */`}</style>

Usage in Next.js:

// pages/index.js
export default function Home() {
  return (
    <div className="container">
      <h1>Welcome to Next.js</h1>
      <p className="description">
        Get started by editing pages/index.js
      </p>
      
      <style jsx>{`
        .container {
          min-height: 100vh;
          padding: 0 0.5rem;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        
        .description {
          text-align: center;
          line-height: 1.5;
          font-size: 1.5rem;
        }
      `}</style>
      
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto;
        }
        
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}

// pages/_app.js (for global styles)
import App from 'next/app';

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    
    return (
      <>
        <Component {...pageProps} />
        <style jsx global>{`
          body {
            font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont;
          }
        `}</style>
      </>
    );
  }
}

export default MyApp;

Configuration Options

Detailed breakdown of all configuration options available.

optimizeForSpeed

Enables CSSOM-based injection for better performance in production.

{
  "plugins": [["styled-jsx/babel", { "optimizeForSpeed": true }]]
}

Effects:

  • Uses CSSOM APIs for faster style injection
  • Reduces bundle size by optimizing style handling
  • Disables source maps (incompatible)
  • Automatically enabled in production (NODE_ENV === 'production')

sourceMaps

Generates source maps for easier debugging during development.

{
  "plugins": [["styled-jsx/babel", { "sourceMaps": true }]]
}

Effects:

  • Enables CSS source map generation
  • Maps compiled CSS back to original JSX
  • Only works when optimizeForSpeed is false
  • Useful for development debugging

styleModule

Customizes the import path for the style component.

{
  "plugins": [["styled-jsx/babel", { "styleModule": "./custom-style-module" }]]
}

Custom Style Module Example:

// custom-style-module.js
import DefaultJSXStyle from 'styled-jsx/style';

export default function CustomJSXStyle(props) {
  // Add custom behavior
  console.log('Style rendered:', props.id);
  
  // Use default implementation
  return DefaultJSXStyle(props);
}

vendorPrefixes

Controls automatic vendor prefix generation.

{
  "plugins": [["styled-jsx/babel", { "vendorPrefixes": false }]]
}

Effects:

  • true (default): Automatically adds vendor prefixes
  • false: Disables vendor prefixing
  • Uses autoprefixer-like functionality

plugins

Array of CSS preprocessing plugins.

{
  "plugins": [
    [
      "styled-jsx/babel", 
      {
        "plugins": [
          "styled-jsx-plugin-postcss",
          ["styled-jsx-plugin-scss", { "sassOptions": {} }]
        ]
      }
    ]
  ]
}

Available Plugins:

// Using PostCSS
{
  "plugins": [
    [
      "styled-jsx/babel",
      {
        "plugins": [
          [
            "styled-jsx-plugin-postcss",
            {
              "plugins": [
                "postcss-nested",
                "autoprefixer"
              ]
            }
          ]
        ]
      }
    ]
  ]
}

// Using Sass
{
  "plugins": [
    [
      "styled-jsx/babel",
      {
        "plugins": [
          [
            "styled-jsx-plugin-sass",
            {
              "sassOptions": {
                "includePaths": ["./styles"]
              }
            }
          ]
        ]
      }
    ]
  ]
}

TypeScript Configuration

Setting up styled-jsx with TypeScript projects.

tsconfig.json:

{
  "compilerOptions": {
    "jsx": "preserve",
    "types": ["styled-jsx"]
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

Custom Type Definitions:

// types/styled-jsx.d.ts
import 'react';

declare module 'react' {
  interface StyleHTMLAttributes<T> extends HTMLAttributes<T> {
    jsx?: boolean;
    global?: boolean;
  }
}

// For css.resolve usage
declare module 'styled-jsx/css' {
  interface ResolveResult {
    className: string;
    styles: JSX.Element;
  }
  
  function resolve(
    template: TemplateStringsArray,
    ...args: any[]
  ): ResolveResult;
}

Install with Tessl CLI

npx tessl i tessl/npm-styled-jsx

docs

babel-macro.md

build-integration.md

component-styling.md

external-css.md

index.md

style-registry.md

tile.json