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

feat: support import typescript files first at dev env #26

Merged
merged 1 commit into from
Dec 23, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 23, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced module import capabilities, particularly for TypeScript files.
    • Introduced new classes (Application, Agent) and an asynchronous function (startCluster) in the project.
    • Added a new package.json for improved module resolution and export management.
  • Bug Fixes

    • Updated debug logging string format for consistency.
  • Tests

    • Added new test cases to validate functionality for TypeScript modules in the import system.

Copy link

vercel bot commented Dec 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
egg-utils ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 23, 2024 10:23am

Copy link

coderabbitai bot commented Dec 23, 2024

Walkthrough

The pull request introduces enhancements to module resolution and TypeScript support in the @eggjs/utils library. The changes focus on improving the importResolve and importModule functions to better handle TypeScript imports. A new test fixture is added to demonstrate TypeScript module support, including a package.json with custom exports and an index.ts file with various exported entities. The modifications extend the library's capability to resolve and import TypeScript modules more robustly, with additional debug logging and file system checks.

Changes

File Change Summary
src/import.ts - Added path and fs imports
- Introduced getRequire() and isSupportTypeScript() private functions
- Enhanced importResolve() to support TypeScript imports
- Updated debug logging
src/plugin.ts - Modified debug logging string format from : to /
test/fixtures/tshy/package.json - New file with framework configuration
- Added TypeScript exports mapping
test/fixtures/tshy/src/index.ts - Added Application and Agent classes
- Introduced startCluster() function
- Added default export and one constant
test/import.test.ts - Added test cases for TypeScript module resolution
- Verified importResolve() and importModule() functionality

Sequence Diagram

sequenceDiagram
    participant Caller
    participant importResolve
    participant getRequire
    participant isSupportTypeScript
    participant FileSystem

    Caller->>importResolve: Call with filepath
    importResolve->>getRequire: Get custom require
    getRequire-->>importResolve: Return require
    importResolve->>isSupportTypeScript: Check TypeScript support
    isSupportTypeScript-->>importResolve: Return support status
    importResolve->>FileSystem: Check file existence
    FileSystem-->>importResolve: Return file info
    importResolve-->>Caller: Return resolved module path
Loading

Poem

🐰 A Rabbit's Module Tale 🐰

In TypeScript's realm, where imports dance,
Our code now leaps with newfound chance,
Resolving paths with graceful might,
Debugging whispers, pure delight!
A module's journey, swift and bright! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

pkg-pr-new bot commented Dec 23, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/utils/@eggjs/utils@26

commit: cab5131

Copy link

codecov bot commented Dec 23, 2024

Codecov Report

Attention: Patch coverage is 97.72727% with 1 line in your changes missing coverage. Please review.

Project coverage is 87.65%. Comparing base (5bb803c) to head (cab5131).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
src/import.ts 97.67% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #26      +/-   ##
==========================================
+ Coverage   86.81%   87.65%   +0.83%     
==========================================
  Files           6        6              
  Lines         440      478      +38     
  Branches       54       63       +9     
==========================================
+ Hits          382      419      +37     
- Misses         58       59       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/import.ts (2)

31-39: Consider extending TypeScript support detection.
Currently, this only checks for '.ts' in require.extensions but ignores '.mts', '.cts', or '.tsx'. If your project expects to handle these additional TS extensions, you should incorporate them.


44-63: Handle potential package.json parse errors.
When reading package.json, a malformed file may cause JSON.parse() to throw an error, which could disrupt your import logic. Consider adding a try/catch to log or handle parse failures gracefully.

   const pkgFile = path.join(filepath, 'package.json');
   if (fs.existsSync(pkgFile)) {
-    const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
+    let pkg;
+    try {
+      pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8'));
+    } catch (err) {
+      debug('[importResolve] failed to parse package.json in %o, error: %o', pkgFile, err);
+      return getRequire().resolve(filepath, { paths });
+    }
     const mainIndexFile = pkg.tshy?.exports?.['.'];
     ...
test/fixtures/tshy/src/index.ts (1)

1-3: Empty classes could benefit from documentation or implementation details.
If Application and Agent need more functionality or clarity, consider adding basic methods or docstrings explaining their purpose.

test/import.test.ts (1)

111-125: Comprehensive test for TS fixture import.
This test checks the entire export set from the TypeScript fixture, including classes, constants, and default exports, providing excellent validation for TS import behavior. Consider adding a negative/invalid-case test if you want to confirm error handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5bb803c and cab5131.

📒 Files selected for processing (5)
  • src/import.ts (2 hunks)
  • src/plugin.ts (1 hunks)
  • test/fixtures/tshy/package.json (1 hunks)
  • test/fixtures/tshy/src/index.ts (1 hunks)
  • test/import.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/tshy/package.json
  • src/plugin.ts
🔇 Additional comments (5)
src/import.ts (3)

4-5: Additions of 'node:path' and 'node:fs' imports look good.
These imports are necessary for path resolution and file system checks. No issues found.


20-29: Efficient fallback for customRequire.
Using createRequire(process.cwd()) is a practical fallback when require is undefined in an ESM environment. This approach is concise and handles multiple runtime contexts gracefully.


41-43: TS import resolution on absolute paths is clear.
The condition ensuring isSupportTypeScript() for absolute paths is straightforward and helps avoid attempts to import TS files when TS is not available.

test/fixtures/tshy/src/index.ts (1)

5-9: Exported default object and constant look good.
The default export pattern here is straightforward, and exporting the constant one allows clear usage in test code. No issues found.

test/import.test.ts (1)

15-17: Good test coverage for TypeScript resolution.
Verifying that importResolve correctly interprets the TypeScript entry point (tshy/src/index.ts) ensures your new TS import logic works as intended.

@fengmk2 fengmk2 merged commit 349c0c3 into master Dec 23, 2024
27 checks passed
@fengmk2 fengmk2 deleted the try-to-ready-tshy-exports-first branch December 23, 2024 11:47
fengmk2 pushed a commit that referenced this pull request Dec 23, 2024
[skip ci]

## [4.1.0](v4.0.3...v4.1.0) (2024-12-23)

### Features

* support import typescript files first at dev env ([#26](#26)) ([349c0c3](349c0c3))
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 this pull request may close these issues.

1 participant