|
| 1 | +module React |
| 2 | + module JSX |
| 3 | + # Depending on the Sprockets version, |
| 4 | + # attach JSX transformation the the Sprockets environment. |
| 5 | + # |
| 6 | + # You can override it with `config.sprockets_strategy` |
| 7 | + # @example Specifying a Sprockets strategy |
| 8 | + # app.config.react.sprockets_strategy = :register_engine |
| 9 | + # |
| 10 | + # @example Opting out of any Sprockets strategy |
| 11 | + # app.config.react.sprockets_strategy = false |
| 12 | + # |
| 13 | + module SprocketsStrategy |
| 14 | + module_function |
| 15 | + |
| 16 | + # @param [Sprockets::Environment] the environment to attach JSX to |
| 17 | + # @param [Symbol, Nil] A strategy name, or `nil` to detect a strategy |
| 18 | + def attach_with_strategy(sprockets_env, strategy_or_nil) |
| 19 | + strategy = strategy_or_nil || detect_strategy |
| 20 | + self.public_send(strategy, sprockets_env) |
| 21 | + end |
| 22 | + |
| 23 | + # @return [Symbol] based on the environment, return a method name to call with the sprockets environment |
| 24 | + def detect_strategy |
| 25 | + sprockets_version = Gem::Version.new(Sprockets::VERSION) |
| 26 | + if sprockets_version >= Gem::Version.new("4.0.0") |
| 27 | + :register_processors |
| 28 | + elsif sprockets_version >= Gem::Version.new("3.0.0") |
| 29 | + :register_engine_with_mime_type |
| 30 | + else |
| 31 | + :register_engine |
| 32 | + end |
| 33 | + end |
| 34 | + |
| 35 | + def register_engine(sprockets_env) |
| 36 | + sprockets_env.register_engine(".jsx", React::JSX::Template) |
| 37 | + end |
| 38 | + |
| 39 | + def register_engine_with_mime_type(sprockets_env) |
| 40 | + sprockets_env.register_engine(".jsx", React::JSX::Processor, mime_type: "application/javascript", silence_deprecation: true) |
| 41 | + end |
| 42 | + |
| 43 | + def register_processors(sprockets_env) |
| 44 | + sprockets_env.register_mime_type("application/jsx", extensions: [".jsx", ".js.jsx", ".es.jsx", ".es6.jsx"]) |
| 45 | + sprockets_env.register_mime_type("application/jsx+coffee", extensions: [".jsx.coffee", ".js.jsx.coffee"]) |
| 46 | + sprockets_env.register_transformer("application/jsx", "application/javascript", React::JSX::Processor) |
| 47 | + sprockets_env.register_transformer("application/jsx+coffee", "application/jsx", Sprockets::CoffeeScriptProcessor) |
| 48 | + sprockets_env.register_preprocessor("application/jsx", Sprockets::DirectiveProcessor.new(comments: ["//", ["/*", "*/"]])) |
| 49 | + sprockets_env.register_preprocessor("application/jsx+coffee", Sprockets::DirectiveProcessor.new(comments: ["#", ["###", "###"]])) |
| 50 | + end |
| 51 | + end |
| 52 | + end |
| 53 | +end |
0 commit comments