rspack icon indicating copy to clipboard operation
rspack copied to clipboard

feat(rslib): handle hashbang / react directives natively

Open fi3ework opened this issue 2 weeks ago • 3 comments

Summary

related Rslib PR https://github.com/web-infra-dev/rslib/pull/1331.

Overview

This PR adds native support for handling hashbang (#!/usr/bin/env node) and React directives ("use client", "use server" and whatever the very first comment that starts with "use ") in both RslibPlugin and EsmLibraryPlugin.

Key Features

1. Hashbang Support

  • Automatically extracts hashbang from module source and places it at the first line of output
  • Sets executable file permissions (0o755) for files with hashbang
  • Works across all output formats (CJS, ESM)

2. React Directives Support

  • Extracts and preserves React directives like "use client" and "use server"
  • Ensures directives are placed at the beginning of the output (after hashbang if present, after "use strict" if present)
  • Always outputs directives with double quotes

Implementation Details

Parser Plugins:

implementated in RslibPlugin, so RslibPlugin is required, which means it won't work with EsmLibraryPlugin alone.

  • HashbangParserPlugin: Extracts hashbang from source code
  • ReactDirectivesParserPlugin: Extracts React directives from source code
  • Both store extracted data in module's build_info.extras

Render Integration:

  • RslibPlugin: Direct source manipulation during render phase for non-ESM formats
  • EsmLibraryPlugin: Uses InitFragment mechanism for ESM format
  • Both plugins have similar logic intentionally (documented with comments) as they handle different output formats with different rendering mechanisms

File Permissions:

  • Implemented in CompilerAssetEmitted hook
  • Uses rspack_fs::FilePermissions for cross-platform compatibility

Utility Functions:

  • Added get_module_hashbang() and get_module_directives() in rspack_core
  • Support for both regular modules and concatenated modules

Related links

Checklist

  • [x] Tests updated (or not required).
  • [ ] Documentation updated (or not required).

fi3ework avatar Nov 12 '25 07:11 fi3ework

Deploy Preview for rspack canceled.

Name Link
Latest commit 520b2e71498c486720b5a2c06b846ae472dd24a4
Latest deploy log https://app.netlify.com/projects/rspack/deploys/6916bd5795f6030008ea575c

netlify[bot] avatar Nov 12 '25 07:11 netlify[bot]

📦 Binary Size-limit

Comparing 520b2e7 to test: rename test script from 'test:rstest' to 'test:base' (#12194) by neverland

❌ Size increased by 18.00KB from 47.45MB to 47.47MB (⬆️0.04%)

github-actions[bot] avatar Nov 12 '25 07:11 github-actions[bot]

CodSpeed Performance Report

Merging #12168 will not alter performance

Comparing hashbang (520b2e7) with main (d2ae8f2)

Summary

✅ 17 untouched

codspeed-hq[bot] avatar Nov 12 '25 08:11 codspeed-hq[bot]