Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserving directive in output #381

Closed
fi3ework opened this issue Nov 7, 2024 · 1 comment · Fixed by #399
Closed

Preserving directive in output #381

fi3ework opened this issue Nov 7, 2024 · 1 comment · Fixed by #399
Assignees

Comments

@fi3ework
Copy link
Member

fi3ework commented Nov 7, 2024

If I want to use rslib to create a component library which supports server components, how can I preserve the "use client" directive at the top of the file?

I have a pretty basic config:

import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  source: {
    entry: {
      index: ['./src/**'],
    },
  },
  lib: [
    {
      bundle: false,
      dts: true,
      format: 'esm',
    },
  ],
  plugins: [
    pluginReact({
      swcReactOptions: {
        runtime: 'classic',
      },
    }),
  ],
});

But my output for a simple client components winds up looking like this:

import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
'use client';
function Counter() {
    const [count, setCount] = __WEBPACK_EXTERNAL_MODULE_react__["default"].useState(0);
    return /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement("div", {
        style: {
            display: 'flex',
            gap: 8,
            padding: 8
        }
    }, /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement("p", null, "Count: ", count), /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement("button", {
        onClick: ()=>setCount((c)=>c + 1)
    }, "Increment"));
}
export { Counter as default };

If "use client"; isn't the first line in the component definition, it's an invalid client component. If I manually move the directive to the top of the file before packing & installing in my consuming app, it works fine. Is there some config options or plugins that exist today to help solve this, or is this currently unsupported?

Originally posted by @rdenman in #379

@fi3ework
Copy link
Member Author

fi3ework commented Nov 7, 2024

Currently, there's not a precise way to preserve the directive. Using `banner (https://lib.rsbuild.dev/config/lib/banner) may works but it's will add banner to all files.

This issue is similar to #166. InitFragment will force inserted the top of the chunk regardless the directive or shebang.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant