Skip to content

fix(nuxt): recompile templates on change events#29954

Merged
danielroe merged 1 commit intomainfrom
fix/recompile-always
Nov 17, 2024
Merged

fix(nuxt): recompile templates on change events#29954
danielroe merged 1 commit intomainfrom
fix/recompile-always

Conversation

@danielroe
Copy link
Member

@danielroe danielroe commented Nov 17, 2024

🔗 Linked issue

resolves #29891

📚 Description

This allows templates to be updated when files change. Also shipped two small perf changes which speed up the compilation.

We might consider on-demand recompilation in future, for example, doing so within the virtual plugin rather than relying on our own watcher.

Summary by CodeRabbit

  • New Features

    • Improved handling of file system events for app component updates, ensuring immediate recompilation after relevant changes.
    • Enhanced logic for managing composables directories, streamlining the import process.
  • Bug Fixes

    • Resolved issues with redundant import path resolution through a new caching mechanism.
  • Refactor

    • Centralized template identification with a new regular expression for better maintainability.
    • Organized the structure of the import handling logic for clarity and efficiency.

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 17, 2024

Walkthrough

The pull request introduces significant modifications to the Nuxt framework's handling of file system events and import management. In builder.ts, the logic for processing file changes has been streamlined to focus on 'add' and 'unlink' events, ensuring that application components are updated correctly. In module.ts, a new regular expression is implemented for identifying import templates, and the organization of composables directory handling has been improved. These changes enhance the maintainability and efficiency of the codebase while ensuring that component updates and imports are managed effectively.

Changes

File Change Summary
packages/nuxt/src/core/builder.ts Removed IS_RESTART_PATH_RE, altered event handling logic to check for 'add' and 'unlink', updated component unset logic, and ensured unconditional call to generateApp.
packages/nuxt/src/imports/module.ts Added IMPORTS_TEMPLATE_RE, reorganized setup function for composables directories, refined regenerateImports function, and implemented caching in addDeclarationTemplates.

Assessment against linked issues

Objective Addressed Explanation
The dependsOn type should automatically update when a referenced plugin's name changes. (#29891) The changes do not address the type inference issue described.

Possibly related PRs

🐇 In the land of code where rabbits play,
Changes hop in, brightening the day.
With imports refined and events in line,
Our Nuxt framework will surely shine!
So let's celebrate with a joyful cheer,
For every tweak brings the future near! 🥕✨


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 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
Contributor

@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

🧹 Outside diff range and nitpick comments (4)
packages/nuxt/src/core/builder.ts (1)

23-35: Enhance component detection patterns

The component detection logic could be improved in the following areas:

  1. The regex patterns ^app\. and ^error\. might match unrelated files (e.g., app.config.ts).
  2. Early breaks in the loops could miss multiple component changes in different layers.

Consider this more specific implementation:

- if (relativePath.match(/^app\./i)) {
+ if (relativePath.match(/^app\.(vue|jsx?|tsx?)$/i)) {
   app.mainComponent = undefined
-  break
 }
- if (relativePath.match(/^error\./i)) {
+ if (relativePath.match(/^error\.(vue|jsx?|tsx?)$/i)) {
   app.errorComponent = undefined
-  break
 }
packages/nuxt/src/imports/module.ts (3)

Line range hint 114-139: Add error handling for directory scanning

While the regeneration logic is solid, consider adding try-catch blocks around the scanning operations to gracefully handle potential file system errors.

 const regenerateImports = async () => {
   await ctx.modifyDynamicImports(async (imports) => {
     // Clear old imports
     imports.length = 0

     // Scan for `composables/` and `utils/` directories
     if (options.scan) {
+      try {
         const scannedImports = await scanDirExports(composablesDirs, {
           fileFilter: file => !isIgnored(file),
         })
         for (const i of scannedImports) {
           i.priority = i.priority || priorities.find(([dir]) => i.from.startsWith(dir))?.[1]
         }
         imports.push(...scannedImports)
+      } catch (error) {
+        logger.warn(`Error scanning composables directories: ${error.message}`)
+      }
     }

     // Modules extending
     await nuxt.callHook('imports:extend', imports)
     return imports
   })

Line range hint 141-156: Consider debouncing rapid file changes

The current implementation might trigger multiple regenerations if several files change in quick succession. Consider implementing debouncing to optimize performance.

+import { debounce } from 'perfect-debounce'
+
+const debouncedRegenerate = debounce(async () => {
+  await regenerateImports()
+}, 100)
+
 // Watch composables/ directory
 nuxt.hook('builder:watch', async (_, relativePath) => {
   const path = resolve(nuxt.options.srcDir, relativePath)
   if (options.scan && composablesDirs.some(dir => dir === path || path.startsWith(dir + '/'))) {
-    await regenerateImports()
+    await debouncedRegenerate()
   }
 })

Line range hint 1-201: Consider implementing on-demand recompilation

As mentioned in the PR objectives, future improvements could include implementing on-demand recompilation through a virtual plugin. This would be more efficient than the current watch-based approach.

Some considerations for the implementation:

  1. Use virtual file system events instead of physical file watching
  2. Implement selective recompilation based on dependency graph
  3. Add cache invalidation hooks for better control
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0a660e8 and 8a70c85.

📒 Files selected for processing (2)
  • packages/nuxt/src/core/builder.ts (1 hunks)
  • packages/nuxt/src/imports/module.ts (1 hunks)
🔇 Additional comments (4)
packages/nuxt/src/core/builder.ts (2)

23-40: Overall implementation looks solid

The changes effectively address the PR objectives by:

  1. Properly handling component changes through layer-aware detection
  2. Ensuring template recompilation when needed
  3. Using debouncing for performance optimization

The implementation is clean, maintainable, and follows Nuxt's architectural patterns.


38-40: 🛠️ Refactor suggestion

Consider conditional template recompilation

The current implementation recompiles templates for all file changes. This might be inefficient for changes that don't affect templates.

Consider adding a condition to check if the changed file actually affects templates:

- // Recompile app templates
- await generateApp()
+ // Recompile app templates only when necessary
+ const isTemplateChange = relativePath.match(/\.(vue|jsx?|tsx?)$/i)
+ if (isTemplateChange) {
+   await generateApp()
+ }

Let's verify the file extensions that require template recompilation:

packages/nuxt/src/imports/module.ts (2)

110-112: Good refactor: Improved template detection logic

Nice improvement to centralize the imports template detection pattern into a regex constant. This makes the code more maintainable and follows the DRY principle.


Line range hint 163-201: Consider cache invalidation strategy

The import path cache is effective for performance, but consider implementing a cache invalidation strategy when dependencies change (e.g., when package.json is modified).

Let's verify if there are any package.json watchers already in place:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DefineNuxtPlugin dependsOn type not updating when referenced plugin name property changes

1 participant