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

Allow loading webpack.config.ts if present #524

Merged
merged 1 commit into from
Oct 31, 2024

Conversation

jdelStrother
Copy link
Contributor

@jdelStrother jdelStrother commented Oct 29, 2024

Summary

This allows configuring webpack from Typescript in config/webpack/webpack.config.ts if it's present.

Further instructions on configuring webpack with typescript are here, but if you've added ts-node & typescript to your package.json that should be all that's needed for webpack.config.ts to just work.

Pull Request checklist

  • Add/update test to cover these changes
  • Update documentation
  • Update CHANGELOG file

Summary by CodeRabbit

  • New Features

    • Introduced a TypeScript-based configuration option for webpack (webpack.config.ts).
  • Bug Fixes

    • Improved error handling for Rails environment loading.
  • Documentation

    • Updated README with installation instructions and upgrade paths for version 8.
    • Enhanced clarity on dependency management and configuration structure.
  • Tests

    • Added a test case to verify loading of TypeScript webpack configuration files.

Copy link

coderabbitai bot commented Oct 29, 2024

Walkthrough

The pull request introduces significant updates to the Shakapacker project, including changes to the changelog, README, and core functionality. Key modifications involve transitioning from require to require_relative, enhancing error handling for Rails environment loading, and adding support for TypeScript-based Webpack configuration. The README has been updated to reflect version changes and installation instructions, while the runner logic has been refactored for improved configuration file detection. New tests have been added to ensure compatibility with the TypeScript configuration.

Changes

File Change Summary
CHANGELOG.md Updated with new entries, modifications, breaking changes, and detailed fixes across versions.
README.md Enhanced documentation for versioning, installation, upgrade paths, and configuration details.
lib/shakapacker/runner.rb Refactored Webpack config file detection logic; added find_webpack_config method.
spec/shakapacker/webpack_runner_spec.rb Added test to verify loading of webpack.config.ts if present.

Possibly related PRs

Suggested reviewers

  • tomdracz

🐇 In the land of code, where changes abound,
A rabbit hops lightly, with joy all around.
With TypeScript in tow, and configs so bright,
We celebrate updates that make coding just right!
So gather your gems, and let’s code with glee,
For Shakapacker’s journey is as sweet as can be! 🌟


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.

@jdelStrother jdelStrother force-pushed the webpack-ts branch 2 times, most recently from 7b3161f to ccc4706 Compare October 29, 2024 13:56
Copy link
Contributor

@G-Rath G-Rath left a comment

Choose a reason for hiding this comment

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

Awesome! I've had this on my to-do for a while, so appreciate you getting this done 🥳

@jdelStrother
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Oct 30, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Outside diff range and nitpick comments (3)
spec/shakapacker/webpack_runner_spec.rb (1)

58-67: LGTM with suggestions for additional test coverage.

The test case correctly verifies the basic TypeScript config loading capability. However, consider enhancing the test suite with additional cases:

Consider adding these test cases for more robust coverage:

it "raises error when webpack.config.ts exists but typescript deps are missing" do
  ts_config = "#{test_app_path}/config/webpack/webpack.config.ts"
  FileUtils.touch(ts_config)
  
  # Simulate missing typescript dependencies
  allow(PackageJson).to receive(:list_dependencies).and_return([])
  
  expect {
    package_json.manager.native_exec_command("webpack", ["--config", ts_config])
  }.to raise_error(/Please add typescript and ts-node to your package.json/)
ensure
  FileUtils.rm(ts_config)
end

it "prioritizes webpack.config.js over webpack.config.ts when both exist" do
  ts_config = "#{test_app_path}/config/webpack/webpack.config.ts"
  js_config = "#{test_app_path}/config/webpack/webpack.config.js"
  FileUtils.touch([ts_config, js_config])
  
  cmd = package_json.manager.native_exec_command("webpack", ["--config", js_config])
  verify_command(cmd)
ensure
  FileUtils.rm([ts_config, js_config])
end
CHANGELOG.md (1)

15-15: Use consistent list style markers

The unordered list uses a dash (-) while other lists in the file use asterisks (*). Consider updating for consistency:

-  - Allow configuring webpack from a Typescript file (`config/webpack/webpack.config.ts`). [PR 524](https://github.com/shakacode/shakapacker/pull/524) by [jdelStrother](https://github.com/jdelStrother).
+  * Allow configuring webpack from a Typescript file (`config/webpack/webpack.config.ts`). [PR 524](https://github.com/shakacode/shakapacker/pull/524) by [jdelStrother](https://github.com/jdelStrother).
🧰 Tools
🪛 Markdownlint

15-15: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

README.md (1)

684-694: Consider enhancing the TypeScript configuration example.

While the TypeScript configuration is correct, it could be improved with type annotations and additional context.

Consider this enhanced version:

 // config/webpack/webpack.config.ts
 import { generateWebpackConfig } from "shakapacker";
 import ForkTSCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
+import type { Configuration } from 'webpack';
 
-const config = generateWebpackConfig({
+const customConfig: Partial<Configuration> = {
   plugins: [new ForkTSCheckerWebpackPlugin()],
-});
+};
+
+const config: Configuration = generateWebpackConfig(customConfig);
 
 export default config;

Also consider adding a note about ensuring tsconfig.json includes the webpack config directory in its compilation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a59be7d and 7c11b4b.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • README.md (1 hunks)
  • lib/shakapacker/runner.rb (1 hunks)
  • spec/shakapacker/webpack_runner_spec.rb (1 hunks)
🧰 Additional context used
🪛 Markdownlint
CHANGELOG.md

15-15: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

🔇 Additional comments (5)
lib/shakapacker/runner.rb (3)

19-19: LGTM: Clean refactor of webpack config initialization

The change elegantly delegates the webpack configuration discovery to a dedicated method, improving code organization and extensibility.


28-29: LGTM: Proper method organization

The private method section follows Ruby conventions and maintains clean code organization.


30-38: 🛠️ Refactor suggestion

Enhance error handling and improve code clarity

While the implementation is functional, there are several opportunities for improvement:

  1. The error message only mentions the JavaScript config file, which could be misleading since TypeScript is also supported.
  2. The single-letter parameter f in the block could be more descriptive.
  3. The error message should mention the TypeScript dependencies requirement.
  4. Consider adding file permission checks for better error handling.

Here's a suggested improvement:

     def find_webpack_config
       possible_paths = %w[ts js].map do |ext|
         File.join(@app_path, "config/webpack/webpack.config.#{ext}")
       end
-      path = possible_paths.find { |f| File.exist?(f) }
+      path = possible_paths.find { |config_path| File.exist?(config_path) && File.readable?(config_path) }
       unless path
-        $stderr.puts "webpack config #{possible_paths.last} not found, please run 'bundle exec rails shakapacker:install' to install Shakapacker with default configs or add the missing config file for your custom environment."
+        $stderr.puts "No webpack config found. Tried: #{possible_paths.join(', ')}\n" \
+                     "Please either:\n" \
+                     "1. Run 'bundle exec rails shakapacker:install' to install Shakapacker with default configs\n" \
+                     "2. Add webpack.config.js for JavaScript configuration\n" \
+                     "3. Add webpack.config.ts and ensure ts-node/typescript are in package.json for TypeScript configuration"
         exit!
       end
       path
     end

Let's verify if the repository has appropriate documentation about the TypeScript requirements:

spec/shakapacker/webpack_runner_spec.rb (1)

58-67: Verify TypeScript dependency handling in the implementation.

The PR description mentions that users need to add ts-node and typescript to their package.json. However, the test doesn't verify if the implementation actually checks for these dependencies.

Let's verify if the dependency check is implemented:

✅ Verification successful

Looking at the implementation in lib/shakapacker/runner.rb, I can now generate a final response:

Implementation correctly handles TypeScript config without explicit dependency checks

The implementation in lib/shakapacker/runner.rb shows that the code automatically looks for both .ts and .js webpack configurations without explicitly checking for TypeScript dependencies. This is actually the correct approach because:

  1. The find_webpack_config method tries TypeScript config first (webpack.config.ts), falling back to JavaScript if not found
  2. If neither config exists, it provides a helpful error message
  3. The actual TypeScript execution is handled by Node.js and requires the dependencies to be present in package.json, which is the correct place for these checks

The current implementation follows the principle of "fail fast" - if TypeScript dependencies are missing, the webpack execution itself will fail with a clear Node.js error about missing dependencies, which is more appropriate than adding redundant dependency checks in the Ruby layer.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for typescript dependency checks in the codebase
rg -l "ts-node|typescript" --type ruby

Length of output: 40


Script:

#!/bin/bash
# Let's check the implementation files for webpack configuration handling
rg -A 10 "webpack.config" --type ruby

Length of output: 11415

README.md (1)

678-682: LGTM: Package installation instructions are clear and complete.

The instructions correctly list all necessary packages for TypeScript webpack configuration.

@justin808 justin808 merged commit f829152 into shakacode:main Oct 31, 2024
26 of 45 checks passed
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.

4 participants