huozhi / bunchee

Zero config bundler for ECMAScript and TypeScript packages
https://npmjs.com/bunchee
859 stars 28 forks source link

'use client' directive should be at the top of the file when combine with `css` import #529

Closed ricomadiko closed 2 months ago

ricomadiko commented 2 months ago

I'm building a component library for Next.js using bunches to compile, and I noticed the __insertCSS function has been placed above the 'use client' directive, which causes Next.js unable to load the file.

Sample component code:

'use client';

import './styles/button.css';

import React, { forwardRef } from 'react';

const Button = forwardRef(function Button(props, ref) {
  const { children, variant = 'primary', ...rest } = props;

  return (
    <button
      className="button"
      data-component="button"
      data-part="root"
      ref={ref}
      {...rest}
    >
      <span>{children}</span>
    </button>
  );
});

Generated code:

function __insertCSS(code) {
  if (!code || typeof document == 'undefined') return
  let head = document.head || document.getElementsByTagName('head')[0]
  let style = document.createElement('style')
  style.type = 'text/css'
  head.appendChild(style)
  ;style.styleSheet ? (style.styleSheet.cssText = code) : style.appendChild(document.createTextNode(code))
}

'use client';
Object.defineProperty(exports, '__esModule', { value: true });

...

Expected behaviour:

__insertCSS function should be added below 'use client'

ricomadiko commented 2 months ago

FYI, the behaviour is correct on v4.4.8 but not in the latest version (v5.1.x)