diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c63f189..a01f77c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ Changes since the last non-beta release. _Please add entries here for your pull requests that are not yet released._ +#### Changed +- Make es6 and ts usable at same time. #1299 + ## [3.1.1] - 2023-08-16 #### Removed diff --git a/lib/generators/react/component_generator.rb b/lib/generators/react/component_generator.rb index f3379316..b069e569 100644 --- a/lib/generators/react/component_generator.rb +++ b/lib/generators/react/component_generator.rb @@ -256,14 +256,20 @@ def lookup(type = "node", options = "") def detect_template_extension if options[:coffee] "js.jsx.coffee" + elsif options[:ts] && es6_enabled? + "es6.tsx" elsif options[:ts] "js.jsx.tsx" - elsif options[:es6] || shakapacker? + elsif es6_enabled? "es6.jsx" else "js.jsx" end end + + def es6_enabled? + options[:es6] || shakapacker? + end end end end diff --git a/lib/generators/templates/component.es6.tsx b/lib/generators/templates/component.es6.tsx new file mode 100644 index 00000000..93206a25 --- /dev/null +++ b/lib/generators/templates/component.es6.tsx @@ -0,0 +1,24 @@ +<%= file_header %> +interface I<%= component_name %>Props { + <% if attributes.size > 0 -%> + <% attributes.each do |attribute| -%> + <% if attribute[:union] -%> + <%= attribute[:name].camelize(:lower) %>: <%= attribute[:name].titleize %>; + <% else -%> + <%= attribute[:name].camelize(:lower) %>: <%= attribute[:type] %>; + <% end -%> + <% end -%> + <% end -%> +} + +const <%= component_name %> = (props: I<%= component_name %>Props) => { + return ( + + <% attributes.each do |attribute| -%> + <%= attribute[:name].titleize %>: {props.<%= attribute[:name].camelize(:lower) %>} + <% end -%> + + ) +} + +<%= file_footer %> diff --git a/test/generators/ts_es6_component_generator_test.rb b/test/generators/ts_es6_component_generator_test.rb new file mode 100644 index 00000000..a5cdb78e --- /dev/null +++ b/test/generators/ts_es6_component_generator_test.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require "test_helper" +require "generators/react/component_generator" + +class TsEs6ComponentGeneratorTest < Rails::Generators::TestCase + destination File.join(Rails.root, "tmp", "component_generator_test_output") + setup :prepare_destination + tests React::Generators::ComponentGenerator + + if ShakapackerHelpers.available? + def filename + "app/javascript/components/GeneratedComponent.tsx" + end + else + def filename + "app/assets/javascripts/components/generated_component.es6.tsx" + end + end + + def component_name + "GeneratedComponent" + end + + test "uses ts and es6 syntax" do + run_generator %w[GeneratedComponent name:string --ts --es6] + + assert_file filename, /const #{component_name} = \(props: I#{component_name}Props\) => {/ + end + + test "defines props type" do + run_generator %w[GeneratedComponent name:string --ts --es6] + + assert_file filename, /name: string;/ + end +end