├── .tool-versions
├── test
├── example_app
│ ├── lib
│ │ ├── assets
│ │ │ └── .keep
│ │ └── tasks
│ │ │ └── .keep
│ ├── vendor
│ │ └── .keep
│ ├── public
│ │ ├── favicon.ico
│ │ ├── apple-touch-icon.png
│ │ ├── apple-touch-icon-precomposed.png
│ │ ├── robots.txt
│ │ ├── 500.html
│ │ ├── 422.html
│ │ └── 404.html
│ ├── .browserslistrc
│ ├── app
│ │ ├── controllers
│ │ │ ├── concerns
│ │ │ │ └── .keep
│ │ │ ├── turbolinks_pages_controller.rb
│ │ │ ├── application_controller.rb
│ │ │ ├── two_packs_controller.rb
│ │ │ ├── custom_tag_controller.rb
│ │ │ └── pages_controller.rb
│ │ ├── javascript
│ │ │ ├── components
│ │ │ │ ├── a.svelte
│ │ │ │ ├── b.svelte
│ │ │ │ └── hello.svelte
│ │ │ └── packs
│ │ │ │ ├── hello_svelte.js
│ │ │ │ ├── a.js
│ │ │ │ ├── b.js
│ │ │ │ ├── turbolinks_hello_svelte.js
│ │ │ │ └── application.js
│ │ └── views
│ │ │ ├── pages
│ │ │ ├── view_component.html.erb
│ │ │ └── view_consecutive.html.erb
│ │ │ ├── custom_tag
│ │ │ └── view_component.html.erb
│ │ │ ├── two_packs
│ │ │ └── view_all.html.erb
│ │ │ └── layouts
│ │ │ ├── turbolinks.html.erb
│ │ │ ├── two_packs.html.erb
│ │ │ └── application.html.erb
│ ├── prettier.config.js
│ ├── bin
│ │ ├── bundle
│ │ ├── webpack-watcher
│ │ ├── rake
│ │ ├── rails
│ │ ├── webpack
│ │ ├── webpack-dev-server
│ │ ├── spring
│ │ ├── update
│ │ └── setup
│ ├── config
│ │ ├── spring.rb
│ │ ├── boot.rb
│ │ ├── environment.rb
│ │ ├── webpack
│ │ │ ├── test.js
│ │ │ ├── development.js
│ │ │ ├── production.js
│ │ │ ├── environment.js
│ │ │ └── loaders
│ │ │ │ └── svelte.js
│ │ ├── initializers
│ │ │ ├── mime_types.rb
│ │ │ ├── application_controller_renderer.rb
│ │ │ ├── filter_parameter_logging.rb
│ │ │ ├── cookies_serializer.rb
│ │ │ ├── backtrace_silencers.rb
│ │ │ ├── wrap_parameters.rb
│ │ │ ├── assets.rb
│ │ │ └── inflections.rb
│ │ ├── routes.rb
│ │ ├── application.rb
│ │ ├── locales
│ │ │ └── en.yml
│ │ ├── secrets.yml
│ │ ├── environments
│ │ │ ├── test.rb
│ │ │ ├── development.rb
│ │ │ └── production.rb
│ │ ├── webpacker.yml
│ │ └── puma.rb
│ ├── config.ru
│ ├── Rakefile
│ ├── postcss.config.js
│ ├── .eslintrc.js
│ ├── package.json
│ └── babel.config.js
├── webpacker
│ ├── react_test.rb
│ └── react
│ │ └── component_test.rb
├── rails_helper.rb
├── integration
│ ├── renderer_with_two_packs_test.rb
│ ├── custom_tag_test.rb
│ ├── renderer_with_turbolinks_test.rb
│ └── renderer_test.rb
└── test_helper.rb
├── _config.yml
├── javascript
└── webpacker_svelte-npm-module
│ ├── .prettierignore
│ ├── prettier.config.js
│ ├── README.md
│ ├── .babelrc
│ ├── rollup.config.js
│ ├── .eslintrc.js
│ ├── package.json
│ └── src
│ ├── index.js
│ └── ujs.js
├── yarn.lock
├── lib
└── webpacker
│ ├── svelte
│ ├── version.rb
│ ├── helpers.rb
│ ├── component.rb
│ └── railtie.rb
│ └── svelte.rb
├── bin
├── setup
└── console
├── Gemfile
├── .gitignore
├── .github
└── PULL_REQUEST_TEMPLATE
├── CHANGELOG.md
├── .circleci
└── config.yml
├── Rakefile
├── LICENSE
├── webpacker-svelte.gemspec
├── .rubocop.yml
├── CODE_OF_CONDUCT.md
├── Gemfile.lock
└── README.md
/.tool-versions:
--------------------------------------------------------------------------------
1 | ruby 2.6.3
2 |
--------------------------------------------------------------------------------
/test/example_app/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/example_app/lib/tasks/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/example_app/vendor/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/test/example_app/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/example_app/.browserslistrc:
--------------------------------------------------------------------------------
1 | defaults
2 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/example_app/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/example_app/public/apple-touch-icon-precomposed.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/.prettierignore:
--------------------------------------------------------------------------------
1 | dist/
--------------------------------------------------------------------------------
/test/example_app/app/javascript/components/a.svelte:
--------------------------------------------------------------------------------
1 |
Component A
2 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/components/b.svelte:
--------------------------------------------------------------------------------
1 | Component B
2 | ;
3 |
--------------------------------------------------------------------------------
/test/example_app/prettier.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | semi: false,
3 | singleQuote: true
4 | }
5 |
--------------------------------------------------------------------------------
/yarn.lock:
--------------------------------------------------------------------------------
1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2 | # yarn lockfile v1
3 |
4 |
5 |
--------------------------------------------------------------------------------
/lib/webpacker/svelte/version.rb:
--------------------------------------------------------------------------------
1 | module Webpacker
2 | module Svelte
3 | VERSION = "1.0.0".freeze
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/prettier.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | semi: false,
3 | singleQuote: true
4 | }
5 |
--------------------------------------------------------------------------------
/test/example_app/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 |
--------------------------------------------------------------------------------
/test/example_app/app/views/pages/view_component.html.erb:
--------------------------------------------------------------------------------
1 | <%= svelte_component('HelloSvelte', name: 'a component rendered from a view') %>
2 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/turbolinks_pages_controller.rb:
--------------------------------------------------------------------------------
1 | class TurbolinksPagesController < PagesController
2 | layout "turbolinks"
3 | end
4 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | protect_from_forgery with: :exception
3 | end
4 |
--------------------------------------------------------------------------------
/test/example_app/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __FILE__)
3 | load Gem.bin_path("bundler", "bundle")
4 |
--------------------------------------------------------------------------------
/test/example_app/config/spring.rb:
--------------------------------------------------------------------------------
1 | %w(
2 | .ruby-version
3 | .rbenv-vars
4 | tmp/restart.txt
5 | tmp/caching-dev.txt
6 | ).each { |path| Spring.watch(path) }
7 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 | IFS=$'\n\t'
4 | set -vx
5 |
6 | bundle install
7 |
8 | # Do any other automated setup that you need to do here
9 |
--------------------------------------------------------------------------------
/test/example_app/app/views/custom_tag/view_component.html.erb:
--------------------------------------------------------------------------------
1 | <%= svelte_component('HelloSvelte', { name: 'a component rendered from a view in a span' }, tag: :span) %>
2 |
--------------------------------------------------------------------------------
/test/example_app/config/boot.rb:
--------------------------------------------------------------------------------
1 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
2 |
3 | require "bundler/setup" # Set up gems listed in the Gemfile.
4 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/two_packs_controller.rb:
--------------------------------------------------------------------------------
1 | class TwoPacksController < ApplicationController
2 | layout "two_packs"
3 |
4 | def view_all
5 | end
6 | end
7 |
--------------------------------------------------------------------------------
/test/example_app/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require_relative "config/environment"
4 |
5 | run Rails.application
6 |
--------------------------------------------------------------------------------
/test/example_app/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative "application"
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/test/example_app/app/views/two_packs/view_all.html.erb:
--------------------------------------------------------------------------------
1 | <%= svelte_component('HelloSvelte', name: 'a component rendered from a view') %>
2 | <%= svelte_component('A') %>
3 | <%= svelte_component('B') %>
4 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/packs/hello_svelte.js:
--------------------------------------------------------------------------------
1 | import WebpackerSvelte from 'webpacker-svelte'
2 |
3 | import HelloSvelte from 'components/hello.svelte'
4 |
5 | WebpackerSvelte.setup({ HelloSvelte })
6 |
--------------------------------------------------------------------------------
/test/example_app/config/webpack/test.js:
--------------------------------------------------------------------------------
1 | process.env.NODE_ENV = process.env.NODE_ENV || 'development'
2 |
3 | const environment = require('./environment')
4 |
5 | module.exports = environment.toWebpackConfig()
6 |
--------------------------------------------------------------------------------
/test/example_app/bin/webpack-watcher:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | BIN_PATH = File.expand_path(".", __dir__)
4 |
5 | Dir.chdir(BIN_PATH) do
6 | exec "./webpack --watch --progress --color #{ARGV.join(" ")}"
7 | end
8 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/test/example_app/config/webpack/development.js:
--------------------------------------------------------------------------------
1 | process.env.NODE_ENV = process.env.NODE_ENV || 'development'
2 |
3 | const environment = require('./environment')
4 |
5 | module.exports = environment.toWebpackConfig()
6 |
--------------------------------------------------------------------------------
/test/example_app/config/webpack/production.js:
--------------------------------------------------------------------------------
1 | process.env.NODE_ENV = process.env.NODE_ENV || 'production'
2 |
3 | const environment = require('./environment')
4 |
5 | module.exports = environment.toWebpackConfig()
6 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/components/hello.svelte:
--------------------------------------------------------------------------------
1 |
4 |
5 |
10 |
11 | Hello, I am {name}!
12 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/README.md:
--------------------------------------------------------------------------------
1 | # webpacker-svelte
2 |
3 | Javascript part for the `webpacker_svelte` Ruby gem.
4 |
5 | Please see the project homepage for more details : https://github.com/will-wow/webpacker-svelte
6 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/packs/a.js:
--------------------------------------------------------------------------------
1 | import WebpackerSvelte from 'webpacker-svelte'
2 | import HelloSvelte from 'components/hello.svelte'
3 | import A from 'components/a.svelte'
4 |
5 | WebpackerSvelte.setup({ A, HelloSvelte })
6 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/packs/b.js:
--------------------------------------------------------------------------------
1 | import WebpackerSvelte from 'webpacker-svelte'
2 | import HelloSvelte from 'components/hello.svelte'
3 | import B from 'components/b.svelte'
4 |
5 | WebpackerSvelte.setup({ HelloSvelte, B })
6 |
--------------------------------------------------------------------------------
/test/example_app/config/webpack/environment.js:
--------------------------------------------------------------------------------
1 | const { environment } = require("@rails/webpacker")
2 | const svelte = require("./loaders/svelte")
3 |
4 | environment.loaders.prepend("svelte", svelte)
5 | module.exports = environment
6 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | [
4 | "env",
5 | {
6 | "targets": {
7 | "browsers": ["> 1%", "last 2 versions"]
8 | }
9 | }
10 | ]
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/test/example_app/config/webpack/loaders/svelte.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | test: /\.svelte$/,
3 | use: [
4 | {
5 | loader: "svelte-loader",
6 | options: {
7 | hotReload: false
8 | }
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/test/example_app/app/views/pages/view_consecutive.html.erb:
--------------------------------------------------------------------------------
1 | <% @count.times do |i| %>
2 | <%= svelte_component('HelloSvelte', name: "component #{i+1}") %>
3 | <% end %>
4 |
5 | <%= link_to "Show 2", count: 2 %>
6 | <%= link_to "Show 3", count: 3 %>
7 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ApplicationController.renderer.defaults.merge!(
4 | # http_host: 'example.org',
5 | # https: false
6 | # )
7 |
--------------------------------------------------------------------------------
/test/webpacker/react_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | module Webpacker
4 | class SvelteTest < Minitest::Test
5 | def test_that_it_has_a_version_number
6 | refute_nil ::Webpacker::Svelte::VERSION
7 | end
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source "https://rubygems.org"
2 |
3 | gem "rubocop", ">= 0.47", require: false
4 | gem "rails", "~> 5.2.0"
5 | gem "webpacker", "~> 4.0.0"
6 | gem "puma", "~> 4.0"
7 |
8 | # Specify your gem's dependencies in webpacker-svelte.gemspec
9 | gemspec
10 |
--------------------------------------------------------------------------------
/test/example_app/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require_relative "config/application"
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/lib/webpacker/svelte.rb:
--------------------------------------------------------------------------------
1 | require "webpacker/svelte/version"
2 |
3 | module Webpacker
4 | module Svelte
5 | end
6 | end
7 |
8 | require "webpacker/svelte/railtie" if defined?(Rails)
9 | require "webpacker/svelte/helpers"
10 | require "webpacker/svelte/component"
11 |
--------------------------------------------------------------------------------
/test/example_app/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path("../spring", __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?("spring")
6 | end
7 | require_relative "../config/boot"
8 | require "rake"
9 | Rake.application.run
10 |
--------------------------------------------------------------------------------
/lib/webpacker/svelte/helpers.rb:
--------------------------------------------------------------------------------
1 | module Webpacker
2 | module Svelte
3 | module Helpers
4 | def svelte_component(component_name, props = {}, options = {})
5 | Webpacker::Svelte::Component.new(component_name).render(props, options)
6 | end
7 | end
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/test/example_app/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: [
3 | require('postcss-import'),
4 | require('postcss-flexbugs-fixes'),
5 | require('postcss-preset-env')({
6 | autoprefixer: {
7 | flexbox: 'no-2009'
8 | },
9 | stage: 3
10 | })
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/test/example_app/app/views/layouts/turbolinks.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WebpackerSvelteExample
5 | <%= csrf_meta_tags %>
6 |
7 | <%= javascript_pack_tag 'turbolinks_hello_svelte' %>
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/example_app/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path("../spring", __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?("spring")
6 | end
7 | APP_PATH = File.expand_path("../config/application", __dir__)
8 | require_relative "../config/boot"
9 | require "rails/commands"
10 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/custom_tag_controller.rb:
--------------------------------------------------------------------------------
1 | class CustomTagController < ApplicationController
2 | def view_component
3 | end
4 |
5 | def controller_component
6 | render svelte_component: "HelloSvelte", props: { name: "a component rendered from a controller in a span" }, tag_options: { tag: :span }
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/test/example_app/app/views/layouts/two_packs.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WebpackerSvelteExample
5 | <%= csrf_meta_tags %>
6 |
7 | <%= javascript_pack_tag 'a' %>
8 | <%= javascript_pack_tag 'b' %>
9 |
10 |
11 |
12 | <%= yield %>
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | /.bundle/
3 | /.yardoc
4 | /_yardoc/
5 | /coverage/
6 | /doc/
7 | /pkg/
8 | /spec/reports/
9 | /tmp/
10 |
11 | /javascript/webpacker_svelte-npm-module/dist/*
12 |
13 | test/example_app/log/*
14 | test/example_app/tmp/*
15 | test/example_app/public/packs
16 | test/example_app/public/packs-test
17 |
18 | .rvmrc
19 |
--------------------------------------------------------------------------------
/test/example_app/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WebpackerSvelteExample
5 | <%= csrf_meta_tags %>
6 |
7 | <%= stylesheet_pack_tag 'hello_svelte' %>
8 | <%= javascript_pack_tag 'hello_svelte' %>
9 |
10 |
11 |
12 | <%= yield %>
13 |
14 |
15 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/rollup.config.js:
--------------------------------------------------------------------------------
1 | import pkg from './package.json'
2 |
3 | export default {
4 | input: './src/index.js',
5 | output: [
6 | {
7 | file: pkg.main,
8 | format: 'cjs',
9 | sourcemap: true
10 | },
11 | {
12 | file: pkg.module,
13 | format: 'es',
14 | sourcemap: true
15 | }
16 | ]
17 | }
18 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE:
--------------------------------------------------------------------------------
1 | Fixes # .
2 |
3 | Changes:
4 |
5 | Please ensure that:
6 | - [ ] Changelog is updated if not a minor patch
7 | - [ ] Ruby linting is ok: `rubocop` is all green
8 | - [ ] Javascript linting is ok: `cd javascript/webpacker_svelte-npm-module/ && yarn lint` is all green
9 | - [ ] [Tests](https://github.com/will-wow/webpacker-svelte#testing) are all green
10 |
--------------------------------------------------------------------------------
/test/example_app/app/controllers/pages_controller.rb:
--------------------------------------------------------------------------------
1 | class PagesController < ApplicationController
2 | def view_component
3 | end
4 |
5 | def view_consecutive
6 | @count = (params[:count] || 2).to_i
7 | end
8 |
9 | def controller_component
10 | render svelte_component: "HelloSvelte", props: { name: "a component rendered from a controller" }
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/packs/turbolinks_hello_svelte.js:
--------------------------------------------------------------------------------
1 | import WebpackerSvelte from 'webpacker-svelte'
2 | import Turbolinks from 'turbolinks'
3 |
4 | import HelloSvelte from 'components/hello.svelte'
5 |
6 | Turbolinks.start()
7 |
8 | if (!window.Turbolinks) {
9 | console.error('Turbolinks failed to install')
10 | }
11 |
12 | WebpackerSvelte.setup({ HelloSvelte })
13 |
--------------------------------------------------------------------------------
/bin/console:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | require "bundler/setup"
4 | require "webpacker/svelte"
5 |
6 | # You can add fixtures and/or initialization code here to make experimenting
7 | # with your gem easier. You can also use a different console, if you like.
8 |
9 | # (If you use this, don't forget to add pry to your Gemfile!)
10 | # require "pry"
11 | # Pry.start
12 |
13 | require "irb"
14 | IRB.start
15 |
--------------------------------------------------------------------------------
/test/rails_helper.rb:
--------------------------------------------------------------------------------
1 | # Configure Rails Environment
2 | ENV["RAILS_ENV"] = "test"
3 |
4 | require File.expand_path("../example_app/config/environment.rb", __FILE__)
5 | require "rails/test_help"
6 | require "rails/generators"
7 | require "pathname"
8 | require "minitest/mock"
9 |
10 | CACHE_PATH = Pathname.new File.expand_path("../example_app/tmp/cache", __FILE__)
11 |
12 | Rails.backtrace_cleaner.remove_silencers!
13 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/test/integration/renderer_with_two_packs_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 | require "irb"
3 |
4 | class RendererWithTwoPacksTest < ActionDispatch::IntegrationTest
5 | test "component mounts" do
6 | require_js
7 |
8 | visit "/two_packs/view_all"
9 | assert_js_error(/Following components are already registered: HelloSvelte/)
10 | assert page.has_content? "Hello, I am a component rendered from a view!"
11 | assert page.has_content? "Component A"
12 | assert page.has_content? "Component B"
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/test/example_app/bin/webpack:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
4 | ENV["NODE_ENV"] ||= "development"
5 |
6 | require "pathname"
7 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
8 | Pathname.new(__FILE__).realpath)
9 |
10 | require "rubygems"
11 | require "bundler/setup"
12 |
13 | require "webpacker"
14 | require "webpacker/webpack_runner"
15 |
16 | APP_ROOT = File.expand_path("..", __dir__)
17 | Dir.chdir(APP_ROOT) do
18 | Webpacker::WebpackRunner.run(ARGV)
19 | end
20 |
--------------------------------------------------------------------------------
/test/example_app/bin/webpack-dev-server:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
4 | ENV["NODE_ENV"] ||= "development"
5 |
6 | require "pathname"
7 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
8 | Pathname.new(__FILE__).realpath)
9 |
10 | require "rubygems"
11 | require "bundler/setup"
12 |
13 | require "webpacker"
14 | require "webpacker/dev_server_runner"
15 |
16 | APP_ROOT = File.expand_path("..", __dir__)
17 | Dir.chdir(APP_ROOT) do
18 | Webpacker::DevServerRunner.run(ARGV)
19 | end
20 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/test/example_app/app/javascript/packs/application.js:
--------------------------------------------------------------------------------
1 | /* eslint no-console:0 */
2 | // This file is automatically compiled by Webpack, along with any other files
3 | // present in this directory. You're encouraged to place your actual application logic in
4 | // a relevant structure within app/javascript and only use these pack files to reference
5 | // that code so it'll be compiled.
6 | //
7 | // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
8 | // layout file, like app/views/layouts/application.html.erb
9 |
10 | console.log('Hello World from Webpacker')
11 |
--------------------------------------------------------------------------------
/test/example_app/bin/spring:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | # This file loads spring without using Bundler, in order to be fast.
4 | # It gets overwritten when you run the `spring binstub` command.
5 |
6 | unless defined?(Spring)
7 | require "rubygems"
8 | require "bundler"
9 |
10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
11 | spring = lockfile.specs.detect { |spec| spec.name == "spring" }
12 | if spring
13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
14 | gem "spring", spring.version
15 | require "spring/binstub"
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parserOptions: {
3 | ecmaVersion: 2019,
4 | sourceType: 'module'
5 | },
6 | env: {
7 | es6: true,
8 | browser: true,
9 | node: true,
10 | jest: true
11 | },
12 | extends: ['eslint:recommended', 'prettier'],
13 | rules: {
14 | 'comma-dangle': ['error', 'never'],
15 | 'import/no-unresolved': 'off',
16 | 'import/no-extraneous-dependencies': 'off',
17 | 'import/extensions': 'off',
18 | 'no-console': 'off',
19 | 'no-new': 'off',
20 | semi: ['error', 'never']
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/lib/webpacker/svelte/component.rb:
--------------------------------------------------------------------------------
1 | module Webpacker
2 | module Svelte
3 | class Component
4 | include ActionView::Helpers::TagHelper
5 | include ActionView::Helpers::TextHelper
6 |
7 | attr_accessor :name
8 |
9 | def initialize(name)
10 | @name = name
11 | end
12 |
13 | def render(props = {}, options = {})
14 | tag = options.delete(:tag) || :div
15 | data = { data: { "svelte-component" => @name, "svelte-props" => props.to_json } }
16 |
17 | content_tag(tag, nil, options.deep_merge(data))
18 | end
19 | end
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/test/integration/custom_tag_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | class CustomTagTest < ActionDispatch::IntegrationTest
4 | test "renders from a view with a custom tag" do
5 | require_js
6 |
7 | visit "/custom_tag_view"
8 | assert_selector "span[data-svelte-component]", text: "Hello, I am a component rendered from a view in a span!"
9 | end
10 |
11 | test "renders from a controller with a custom tag" do
12 | require_js
13 |
14 | visit "/custom_tag_controller"
15 | assert_selector "span[data-svelte-component]", text: "Hello, I am a component rendered from a controller in a span!"
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](http://keepachangelog.com/)
6 | and this project adheres to [Semantic Versioning](http://semver.org/).
7 |
8 | ## [1.0.0]
9 |
10 | ### Changed
11 |
12 | - There haven't been any bugs reported, so this can be considered stable. Bump version to 1.0.0.
13 | - rename main branch from `master` to `main`
14 |
15 | ## [0.1.0]
16 |
17 | ### Changed
18 |
19 | - Used rollup and lodash-modularized packages for smaller builds
20 |
21 | ## [0.0.0]
22 |
23 | ### Added
24 |
25 | - Ported over from [webpacker-react](https://github.com/renchap/webpacker-react)
26 |
--------------------------------------------------------------------------------
/test/example_app/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parserOptions: {
3 | ecmaVersion: 2019,
4 | sourceType: 'module'
5 | },
6 | env: {
7 | es6: true,
8 | browser: true,
9 | node: true,
10 | jest: true
11 | },
12 | extends: ['eslint:recommended', 'prettier'],
13 | rules: {
14 | 'comma-dangle': ['error', 'never'],
15 | 'import/no-unresolved': 'off',
16 | 'import/no-extraneous-dependencies': 'off',
17 | 'import/extensions': 'off',
18 | 'no-console': 'off',
19 | semi: ['error', 'never']
20 | },
21 | plugins: ['svelte3'],
22 | overrides: [
23 | {
24 | files: ['**/*.svelte'],
25 | processor: 'svelte3/svelte3'
26 | }
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/test/example_app/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | get "/view", to: "pages#view_component"
3 | get "/view_consecutive", to: "pages#view_consecutive"
4 | get "/controller", to: "pages#controller_component"
5 |
6 | get "/turbolinks/view", to: "turbolinks_pages#view_component"
7 | get "/turbolinks/view_consecutive", to: "turbolinks_pages#view_consecutive"
8 | get "/turbolinks/controller", to: "turbolinks_pages#controller_component"
9 |
10 | get "/two_packs/view_all", to: "two_packs#view_all"
11 |
12 | get "/custom_tag_view", to: "custom_tag#view_component"
13 | get "/custom_tag_controller", to: "custom_tag#controller_component"
14 |
15 | root to: "pages#view_component"
16 | end
17 |
--------------------------------------------------------------------------------
/test/integration/renderer_with_turbolinks_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 | require_relative "./renderer_test"
3 |
4 | class RendererWithTurbolinksTest < RendererTest
5 | def url_prefix
6 | "/turbolinks"
7 | end
8 |
9 | test "Turbolinks visits" do
10 | require_js
11 |
12 | visit url_prefix + "/view_consecutive"
13 |
14 | assert page.has_content? "component 1"
15 | assert page.has_content? "component 2"
16 |
17 | click_link "Show 3"
18 |
19 | assert page.has_content? "component 3"
20 |
21 | click_link "Show 2"
22 |
23 | assert page.has_content? "component 1"
24 | assert page.has_content? "component 2"
25 | assert page.has_no_content? "component 3"
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = "1.0"
5 |
6 | # Add additional assets to the asset load path.
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 | # Add Yarn node_modules folder to the asset load path.
9 | Rails.application.config.assets.paths << Rails.root.join("vendor/node_modules")
10 |
11 | # Precompile additional assets.
12 | # application.js, application.css, and all non-JS/CSS in the app/assets
13 | # folder are already added.
14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css )
15 |
--------------------------------------------------------------------------------
/test/example_app/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/test/example_app/bin/update:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require "pathname"
3 | require "fileutils"
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path("../../", __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a way to update your development environment automatically.
15 | # Add necessary update steps to this file.
16 |
17 | puts "== Installing dependencies =="
18 | system! "gem install bundler --conservative"
19 | system("bundle check") || system!("bundle install")
20 |
21 | puts "\n== Removing old logs and tempfiles =="
22 | system! "bin/rails log:clear tmp:clear"
23 |
24 | puts "\n== Restarting application server =="
25 | system! "bin/rails restart"
26 | end
27 |
--------------------------------------------------------------------------------
/test/integration/renderer_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | class RendererTest < ActionDispatch::IntegrationTest
4 | def url_prefix
5 | ""
6 | end
7 |
8 | test "renders from a view" do
9 | get url_prefix + "/view"
10 | assert_select "div[data-svelte-component]", true
11 | end
12 |
13 | test "renders from a controller" do
14 | get url_prefix + "/controller"
15 | assert_select "div[data-svelte-component]", true
16 | end
17 |
18 | test "component mounts" do
19 | require_js
20 |
21 | visit url_prefix + "/view"
22 | assert page.has_content? "Hello, I am a component rendered from a view!"
23 | end
24 |
25 | test "consecutive components mounts" do
26 | require_js
27 |
28 | visit url_prefix + "/view_consecutive"
29 |
30 | assert page.has_content? "component 1"
31 | assert page.has_content? "component 2"
32 | end
33 | end
34 |
--------------------------------------------------------------------------------
/test/example_app/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require "pathname"
3 | require "fileutils"
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path("../../", __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a starting point to setup your application.
15 | # Add necessary setup steps to this file.
16 |
17 | puts "== Installing dependencies =="
18 | system! "gem install bundler --conservative"
19 | system("bundle check") || system!("bundle install")
20 |
21 | # Install JavaScript dependencies if using Yarn
22 | # system('bin/yarn')
23 |
24 | puts "\n== Removing old logs and tempfiles =="
25 | system! "bin/rails log:clear tmp:clear"
26 |
27 | puts "\n== Restarting application server =="
28 | system! "bin/rails restart"
29 | end
30 |
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | working_directory: ~/webpacker-svelte
5 | docker:
6 | - image: circleci/ruby:2.4.3-node-browsers
7 | environment:
8 | RAILS_ENV: test
9 | steps:
10 | - checkout
11 |
12 | # Install dependencies
13 | - run:
14 | name: bundle install
15 | command: bundle install --path=vendor/bundle --jobs=4 --retry=3
16 | - run:
17 | command: yarn
18 | pwd: javascript/webpacker_svelte-npm-module
19 | - run:
20 | command: yarn
21 | pwd: javascript/webpacker_svelte-npm-module/dist
22 |
23 | # Lint
24 | - run:
25 | command: yarn lint
26 | pwd: javascript/webpacker_svelte-npm-module
27 | - run:
28 | command: bundle exec rubocop
29 |
30 | # Tests
31 | - run:
32 | command: bundle exec rake test
33 |
--------------------------------------------------------------------------------
/test/example_app/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative "boot"
2 |
3 | require "rails"
4 | # Pick the frameworks you want:
5 | require "active_model/railtie"
6 | require "active_job/railtie"
7 | # require "active_record/railtie"
8 | require "action_controller/railtie"
9 | # require "action_mailer/railtie"
10 | require "action_view/railtie"
11 | # require "action_cable/engine"
12 | require "sprockets/railtie"
13 | require "rails/test_unit/railtie"
14 |
15 | # Require the gems listed in Gemfile, including any gems
16 | # you've limited to :test, :development, or :production.
17 | Bundler.require(*Rails.groups)
18 |
19 | module WebpackerSvelteExample
20 | class Application < Rails::Application
21 | # Settings in config/environments/* take precedence over those specified here.
22 | # Application configuration should go into files in config/initializers
23 | # -- all .rb files in that directory are automatically loaded.
24 | end
25 | end
26 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | require "bundler/gem_tasks"
2 | require "rake/testtask"
3 | require "English"
4 |
5 | Rake::TestTask.new(:test) do |t|
6 | t.libs << "test"
7 | t.libs << "lib"
8 | t.test_files = FileList["test/**/*_test.rb"]
9 | t.verbose = true
10 | end
11 |
12 | task default: :test
13 |
14 | # webpacker:check_webpack_binstubs is looking for binstubs
15 | # in the gem root directory. We need to disable it for our
16 | # tests, as it tries to check they exist when loading the
17 | # example app
18 |
19 | task "webpacker:check_webpack_binstubs"
20 | Rake::Task["webpacker:check_webpack_binstubs"].clear
21 |
22 | namespace :example_app do
23 | desc "Runs yarn in test/example_app"
24 | task :yarn do
25 | sh "cd test/example_app && yarn"
26 | end
27 |
28 | desc "Runs webpack in test/example_app"
29 | task webpack: :yarn do
30 | sh "cd test/example_app && RAILS_ENV=test ./bin/webpack"
31 | end
32 | end
33 |
34 | Rake::Task["test"].enhance ["example_app:webpack"]
35 |
--------------------------------------------------------------------------------
/lib/webpacker/svelte/railtie.rb:
--------------------------------------------------------------------------------
1 | require "rails/railtie"
2 |
3 | module Webpacker
4 | module Svelte
5 | class Engine < ::Rails::Engine
6 | initializer :webpacker_svelte do
7 | ActiveSupport.on_load(:action_controller) do
8 | ActionController::Base.helper ::Webpacker::Svelte::Helpers
9 | end
10 |
11 | ActiveSupport.on_load :action_view do
12 | include ::Webpacker::Svelte::Helpers
13 | end
14 | end
15 |
16 | initializer :webpacker_svelte_renderer, group: :all do |_app|
17 | ActionController::Renderers.add :svelte_component do |component_name, options|
18 | props = options.fetch(:props, {})
19 | tag_options = options.fetch(:tag_options, {})
20 | html = Webpacker::Svelte::Component.new(component_name).render(props, tag_options)
21 | render_options = options.merge(inline: html)
22 | render(render_options)
23 | end
24 | end
25 | end
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/test/example_app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "dependencies": {
4 | "@rails/webpacker": "^4.0.7",
5 | "prop-types": "^15.7.2",
6 | "svelte": "^3.9.1",
7 | "turbolinks": "^5.2.0",
8 | "webpacker-svelte": "0.1.0"
9 | },
10 | "devDependencies": {
11 | "eslint": "^6.3.0",
12 | "eslint-config-prettier": "^6.2.0",
13 | "eslint-plugin-import": "^2.18.2",
14 | "eslint-plugin-svelte3": "^2.7.3",
15 | "npm-run-all": "^4.1.5",
16 | "prettier": "^1.18.2",
17 | "prettier-plugin-svelte": "^0.7.0",
18 | "svelte-loader": "^2.13.6",
19 | "webpack-dev-server": "^3.7.2"
20 | },
21 | "scripts": {
22 | "lint": "npm-run-all -c lint:*",
23 | "lint:prettier": "prettier --check '**/*.{js,json,md,svelte}'",
24 | "lint:eslint": "eslint app/javascript/",
25 | "format": "npm-run-all -c format:*",
26 | "format:eslint": "eslint --fix app/javascript/",
27 | "format:prettier": "prettier --write '**/*.{js,json,md,svelte}'"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/test/example_app/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # The following keys must be escaped otherwise they will not be retrieved by
20 | # the default I18n backend:
21 | #
22 | # true, false, on, off, yes, no
23 | #
24 | # Instead, surround them with single quotes.
25 | #
26 | # en:
27 | # 'true': 'foo'
28 | #
29 | # To learn more, please read the Rails Internationalization guide
30 | # available at http://guides.rubyonrails.org/i18n.html.
31 |
32 | en:
33 | hello: "Hello world"
34 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Renaud Chaput
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/test/example_app/config/secrets.yml:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Your secret key is used for verifying the integrity of signed cookies.
4 | # If you change this key, all old signed cookies will become invalid!
5 |
6 | # Make sure the secret is at least 30 characters and all random,
7 | # no regular words or you'll be exposed to dictionary attacks.
8 | # You can use `rails secret` to generate a secure secret key.
9 |
10 | # Make sure the secrets in this file are kept private
11 | # if you're sharing your code publicly.
12 |
13 | # Shared secrets are available across all environments.
14 |
15 | shared:
16 | api_key: 123
17 |
18 | # Environmental secrets are only available for that specific environment.
19 |
20 | development:
21 | secret_key_base: ed9ddd0ab3bcf6d5e48a1458fdd01ab881b9d81a9aed9721c613b882288a1d4c353183c8af848fd2b6a0144d4363d68ba8d3b1777a60dec6c47d2982859af718
22 |
23 | test:
24 | secret_key_base: 019daa9abf5f3a865af821a074792fd39908d1d53925a97fa1f063af729a8ca6c7b0e086836567139f3f091caa8c4ed1f2393a5deff440240c2e794c7e19b788
25 |
26 | # Do not keep production secrets in the repository,
27 | # instead read values from the environment.
28 |
29 | production:
30 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
31 |
--------------------------------------------------------------------------------
/webpacker-svelte.gemspec:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | lib = File.expand_path("../lib", __FILE__)
3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4 | require "webpacker/svelte/version"
5 |
6 | Gem::Specification.new do |spec|
7 | spec.name = "webpacker-svelte"
8 | spec.licenses = ["MIT"]
9 | spec.version = Webpacker::Svelte::VERSION
10 | spec.authors = ["Will Ockelmann-Wagner"]
11 | spec.email = ["will.ockelmann.wagner@gmail.com"]
12 |
13 | spec.summary = "Provides Svelte integration for Webpacker"
14 | # spec.description = %q{TODO: Write a longer description or delete this line.}
15 | spec.homepage = "https://github.com/will-wow/webpacker-svelte"
16 |
17 | spec.files = `git ls-files -z`.split("\x0").reject do |f|
18 | f.match(%r{^(test|spec|features)/})
19 | end
20 | spec.bindir = "exe"
21 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22 | spec.require_paths = ["lib"]
23 |
24 | spec.required_ruby_version = ">= 2.3.0"
25 |
26 | spec.add_dependency "webpacker"
27 |
28 | spec.add_development_dependency "bundler", "~> 1.13"
29 | spec.add_development_dependency "rake", "~> 12.0"
30 | spec.add_development_dependency "minitest", "~> 5.0"
31 | spec.add_development_dependency "capybara"
32 | spec.add_development_dependency "selenium-webdriver"
33 | end
34 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "webpacker-svelte",
3 | "version": "1.0.0",
4 | "description": "webpacker-svelte integration",
5 | "homepage": "https://github.com/will-wow/webpacker-svelte",
6 | "repository": "will-wow/webpacker-svelte",
7 | "author": {
8 | "name": "Will Ockelmann-Wagner",
9 | "email": "will@willwow.dev"
10 | },
11 | "license": "MIT",
12 | "main": "dist/webpacker-svelte.cjs.js",
13 | "module": "dist/webpacker-svelte.js",
14 | "keywords": [
15 | "svelte",
16 | "webpacker"
17 | ],
18 | "files": [
19 | "dist/**/*",
20 | "src/**/*"
21 | ],
22 | "scripts": {
23 | "build": "rollup -c",
24 | "prepublishOnly": "npm run lint",
25 | "lint": "npm-run-all -c lint:*",
26 | "lint:prettier": "prettier --check '**/*.{js,json,md,svelte}'",
27 | "lint:eslint": "eslint src/",
28 | "format": "npm-run-all -c format:*",
29 | "format:eslint": "eslint --fix src/",
30 | "format:prettier": "prettier --write '**/*.{js,json,md,svelte}'"
31 | },
32 | "devDependencies": {
33 | "babel-cli": "^6.26.0",
34 | "babel-preset-env": "^1.7.0",
35 | "eslint": "^6.3.0",
36 | "eslint-config-prettier": "^6.2.0",
37 | "eslint-plugin-import": "^2.18.2",
38 | "npm-run-all": "^4.1.5",
39 | "prettier": "^1.18.2",
40 | "rollup": "^1.21.2"
41 | },
42 | "peerDependencies": {
43 | "svelte": ">= 3"
44 | },
45 | "dependencies": {
46 | "lodash.assign": "^4.2.0",
47 | "lodash.intersection": "^4.4.0",
48 | "lodash.keys": "^4.2.0",
49 | "lodash.omit": "^4.5.0"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/test/example_app/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # The test environment is used exclusively to run your application's
5 | # test suite. You never need to work with it otherwise. Remember that
6 | # your test database is "scratch space" for the test suite and is wiped
7 | # and recreated between test runs. Don't rely on the data there!
8 | config.cache_classes = true
9 |
10 | # Do not eager load code on boot. This avoids loading your whole application
11 | # just for the purpose of running a single test. If you are using a tool that
12 | # preloads Rails for running tests, you may have to set it to true.
13 | config.eager_load = false
14 |
15 | # Configure public file server for tests with Cache-Control for performance.
16 | config.public_file_server.enabled = true
17 | config.public_file_server.headers = {
18 | "Cache-Control" => "public, max-age=#{1.hour.seconds.to_i}"
19 | }
20 |
21 | # Show full error reports and disable caching.
22 | config.consider_all_requests_local = true
23 | config.action_controller.perform_caching = false
24 |
25 | # Raise exceptions instead of rendering exception templates.
26 | config.action_dispatch.show_exceptions = false
27 |
28 | # Disable request forgery protection in test environment.
29 | config.action_controller.allow_forgery_protection = false
30 |
31 | # Print deprecation notices to the stderr.
32 | config.active_support.deprecation = :stderr
33 |
34 | # Raises error for missing translations
35 | # config.action_view.raise_on_missing_translations = true
36 | end
37 |
--------------------------------------------------------------------------------
/test/example_app/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/test/example_app/config/webpacker.yml:
--------------------------------------------------------------------------------
1 | # Note: You must restart bin/webpack-dev-server for changes to take effect
2 |
3 | default: &default
4 | source_path: app/javascript
5 | source_entry_path: packs
6 | public_root_path: public
7 | public_output_path: packs
8 | cache_path: tmp/cache/webpacker
9 | check_yarn_integrity: false
10 | webpack_compile_output: false
11 |
12 | # Additional paths webpack should lookup modules
13 | # ['app/assets', 'engine/foo/app/assets']
14 | resolved_paths: []
15 |
16 | # Reload manifest.json on all requests so we reload latest compiled packs
17 | cache_manifest: false
18 |
19 | # Extract and emit a css file
20 | extract_css: false
21 |
22 | static_assets_extensions:
23 | - .jpg
24 | - .jpeg
25 | - .png
26 | - .gif
27 | - .tiff
28 | - .ico
29 | - .svg
30 | - .eot
31 | - .otf
32 | - .ttf
33 | - .woff
34 | - .woff2
35 |
36 | extensions:
37 | - .jsx
38 | - .mjs
39 | - .js
40 | - .sass
41 | - .scss
42 | - .css
43 | - .module.sass
44 | - .module.scss
45 | - .module.css
46 | - .png
47 | - .svg
48 | - .gif
49 | - .jpeg
50 | - .jpg
51 |
52 | development:
53 | <<: *default
54 | compile: false
55 |
56 | # Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
57 | check_yarn_integrity: true
58 |
59 | test:
60 | <<: *default
61 | compile: false
62 |
63 | # Compile test packs to a separate directory
64 | public_output_path: packs-test
65 |
66 | production:
67 | <<: *default
68 |
69 | # Production depends on precompilation of packs prior to booting for performance.
70 | compile: false
71 |
72 | # Extract and emit a css file
73 | extract_css: true
74 |
75 | # Cache manifest.json for performance
76 | cache_manifest: true
77 |
--------------------------------------------------------------------------------
/test/example_app/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/test/example_app/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
2 |
3 | require "rails_helper"
4 | require "webpacker/svelte"
5 | require "minitest/autorun"
6 | require "capybara/rails"
7 |
8 | require "selenium/webdriver"
9 |
10 | Capybara.register_driver :headless_chrome do |app|
11 | capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
12 | chromeOptions: { args: %w(headless disable-gpu) }
13 | )
14 |
15 | Capybara::Selenium::Driver.new app,
16 | browser: :chrome,
17 | desired_capabilities: capabilities
18 | end
19 |
20 | Capybara.javascript_driver = :headless_chrome
21 |
22 | class ActionDispatch::IntegrationTest
23 | class DriverJSError < StandardError; end
24 | include Capybara::DSL
25 |
26 | def setup
27 | @ignored_js_errors = []
28 | end
29 |
30 | def teardown
31 | if Capybara.current_driver == :headless_chrome
32 | errors = current_js_errors.select do |message|
33 | # If the message matches any ones ignored, skip it
34 | puts "==="
35 | puts @ignored_js_errors.inspect
36 | puts message
37 | !@ignored_js_errors.any? { |e| !(message =~ e) }
38 | end
39 |
40 | assert errors.empty?, "Got JS errors: \n#{errors.join("\n\n")}"
41 | end
42 |
43 | Capybara.current_driver = nil
44 | end
45 |
46 | def require_js
47 | Capybara.current_driver = Capybara.javascript_driver
48 | end
49 |
50 | def current_js_errors
51 | page.driver.browser.manage.logs.get(:browser)
52 | .select { |e| e.level == "SEVERE" && message.present? }
53 | .map(&:message)
54 | .to_a
55 | end
56 |
57 | def assert_js_error(error_match)
58 | error = current_js_errors.find { |e| e. =~ error_match }
59 |
60 | if error
61 | @ignored_js_errors << error
62 | else
63 | puts error.to_s
64 | assert false, "Expected a JS error matching: #{error_match.to_s}"
65 | end
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/test/example_app/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Make javascript_pack_tag load assets from webpack-dev-server.
3 | # config.x.webpacker[:dev_server_host] = "http://localhost:8080"
4 |
5 | # Settings specified here will take precedence over those in config/application.rb.
6 |
7 | # In the development environment your application's code is reloaded on
8 | # every request. This slows down response time but is perfect for development
9 | # since you don't have to restart the web server when you make code changes.
10 | config.cache_classes = false
11 |
12 | # Do not eager load code on boot.
13 | config.eager_load = false
14 |
15 | # Show full error reports.
16 | config.consider_all_requests_local = true
17 |
18 | # Enable/disable caching. By default caching is disabled.
19 | if Rails.root.join("tmp/caching-dev.txt").exist?
20 | config.action_controller.perform_caching = true
21 |
22 | config.cache_store = :memory_store
23 | config.public_file_server.headers = {
24 | "Cache-Control" => "public, max-age=#{2.days.seconds.to_i}"
25 | }
26 | else
27 | config.action_controller.perform_caching = false
28 |
29 | config.cache_store = :null_store
30 | end
31 |
32 | # Print deprecation notices to the Rails logger.
33 | config.active_support.deprecation = :log
34 |
35 | # Debug mode disables concatenation and preprocessing of assets.
36 | # This option may cause significant delays in view rendering with a large
37 | # number of complex assets.
38 | config.assets.debug = true
39 |
40 | # Suppress logger output for asset requests.
41 | config.assets.quiet = true
42 |
43 | # Raises error for missing translations
44 | # config.action_view.raise_on_missing_translations = true
45 |
46 | # Use an evented file watcher to asynchronously detect changes in source code,
47 | # routes, locales, etc. This feature depends on the listen gem.
48 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker
49 | end
50 |
--------------------------------------------------------------------------------
/test/example_app/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = function(api) {
2 | var validEnv = ['development', 'test', 'production']
3 | var currentEnv = api.env()
4 | var isDevelopmentEnv = api.env('development')
5 | var isProductionEnv = api.env('production')
6 | var isTestEnv = api.env('test')
7 |
8 | if (!validEnv.includes(currentEnv)) {
9 | throw new Error(
10 | 'Please specify a valid `NODE_ENV` or ' +
11 | '`BABEL_ENV` environment variables. Valid values are "development", ' +
12 | '"test", and "production". Instead, received: ' +
13 | JSON.stringify(currentEnv) +
14 | '.'
15 | )
16 | }
17 |
18 | return {
19 | presets: [
20 | isTestEnv && [
21 | require('@babel/preset-env').default,
22 | {
23 | targets: {
24 | node: 'current'
25 | }
26 | }
27 | ],
28 | (isProductionEnv || isDevelopmentEnv) && [
29 | require('@babel/preset-env').default,
30 | {
31 | forceAllTransforms: true,
32 | useBuiltIns: 'entry',
33 | corejs: 3,
34 | modules: false,
35 | exclude: ['transform-typeof-symbol']
36 | }
37 | ]
38 | ].filter(Boolean),
39 | plugins: [
40 | require('babel-plugin-macros'),
41 | require('@babel/plugin-syntax-dynamic-import').default,
42 | isTestEnv && require('babel-plugin-dynamic-import-node'),
43 | require('@babel/plugin-transform-destructuring').default,
44 | [
45 | require('@babel/plugin-proposal-class-properties').default,
46 | {
47 | loose: true
48 | }
49 | ],
50 | [
51 | require('@babel/plugin-proposal-object-rest-spread').default,
52 | {
53 | useBuiltIns: true
54 | }
55 | ],
56 | [
57 | require('@babel/plugin-transform-runtime').default,
58 | {
59 | helpers: false,
60 | regenerator: true,
61 | corejs: false
62 | }
63 | ],
64 | [
65 | require('@babel/plugin-transform-regenerator').default,
66 | {
67 | async: false
68 | }
69 | ],
70 | ].filter(Boolean)
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/javascript/webpacker_svelte-npm-module/src/index.js:
--------------------------------------------------------------------------------
1 | import intersection from 'lodash.intersection'
2 | import keys from 'lodash.keys'
3 | import assign from 'lodash.assign'
4 | import omit from 'lodash.omit'
5 | import ujs from './ujs'
6 |
7 | const CLASS_ATTRIBUTE_NAME = 'data-svelte-component'
8 | const PROPS_ATTRIBUTE_NAME = 'data-svelte-props'
9 |
10 | const noop = () => {}
11 |
12 | const WebpackerSvelte = {
13 | registeredComponents: {},
14 |
15 | render(node, Component) {
16 | const propsJson = node.getAttribute(PROPS_ATTRIBUTE_NAME)
17 | const props = propsJson && JSON.parse(propsJson)
18 |
19 | new Component({
20 | target: node,
21 | props
22 | })
23 | },
24 |
25 | registerComponents(components) {
26 | const collisions = intersection(
27 | keys(this.registeredComponents),
28 | keys(components)
29 | )
30 | if (collisions.length > 0) {
31 | console.error(
32 | `webpacker-svelte: can not register components. Following components are already registered: ${collisions}`
33 | )
34 | }
35 |
36 | assign(this.registeredComponents, omit(components, collisions))
37 | return true
38 | },
39 |
40 | mountComponents() {
41 | const { registeredComponents } = this
42 | const toMount = document.querySelectorAll(`[${CLASS_ATTRIBUTE_NAME}]`)
43 |
44 | for (let i = 0; i < toMount.length; i += 1) {
45 | const node = toMount[i]
46 | const className = node.getAttribute(CLASS_ATTRIBUTE_NAME)
47 | const component = registeredComponents[className]
48 |
49 | if (component) {
50 | if (node.innerHTML.length === 0) this.render(node, component)
51 | } else {
52 | console.error(
53 | `webpacker-svelte: can not render a component that has not been registered: ${className}`
54 | )
55 | }
56 | }
57 | },
58 |
59 | setup(components = {}) {
60 | if (typeof window.WebpackerSvelte === 'undefined') {
61 | window.WebpackerSvelte = this
62 | ujs.setup(this.mountComponents.bind(this), noop)
63 | }
64 |
65 | window.WebpackerSvelte.registerComponents(components)
66 | window.WebpackerSvelte.mountComponents()
67 | }
68 | }
69 |
70 | export default WebpackerSvelte
71 |
--------------------------------------------------------------------------------
/test/example_app/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers: a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum; this matches the default thread size of Active Record.
6 | #
7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
8 | threads threads_count, threads_count
9 |
10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000.
11 | #
12 | port ENV.fetch("PORT") { 3000 }
13 |
14 | # Specifies the `environment` that Puma will run in.
15 | #
16 | environment ENV.fetch("RAILS_ENV") { "development" }
17 |
18 | # Specifies the number of `workers` to boot in clustered mode.
19 | # Workers are forked webserver processes. If using threads and workers together
20 | # the concurrency of the application would be max `threads` * `workers`.
21 | # Workers do not work on JRuby or Windows (both of which do not support
22 | # processes).
23 | #
24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
25 |
26 | # Use the `preload_app!` method when specifying a `workers` number.
27 | # This directive tells Puma to first boot the application and load code
28 | # before forking the application. This takes advantage of Copy On Write
29 | # process behavior so workers use less memory. If you use this option
30 | # you need to make sure to reconnect any threads in the `on_worker_boot`
31 | # block.
32 | #
33 | # preload_app!
34 |
35 | # If you are preloading your application and using Active Record, it's
36 | # recommended that you close any connections to the database before workers
37 | # are forked to prevent connection leakage.
38 | #
39 | # before_fork do
40 | # ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord)
41 | # end
42 |
43 | # The code in the `on_worker_boot` will be called if you are using
44 | # clustered mode by specifying a number of `workers`. After each worker
45 | # process is booted, this block will be run. If you are using the `preload_app!`
46 | # option, you will want to use this block to reconnect to any threads
47 | # or connections that may have been created at application boot, as Ruby
48 | # cannot share connections between processes.
49 | #
50 | # on_worker_boot do
51 | # ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
52 | # end
53 | #
54 |
55 | # Allow puma to be restarted by `rails restart` command.
56 | plugin :tmp_restart
57 |
--------------------------------------------------------------------------------
/test/webpacker/react/component_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | module Webpacker
4 | module Svelte
5 | class ComponentTest < Minitest::Test
6 | include ERB::Util
7 |
8 | def setup
9 | @component = {
10 | name: "Hello",
11 | props: {
12 | name: "Svelte"
13 | }
14 | }
15 | end
16 |
17 | def test_it_outputs_a_div_element
18 | expected_html = <<-HTML.squish
19 |
21 | HTML
22 | html = Webpacker::Svelte::Component.new(@component[:name])
23 | .render(@component[:props])
24 |
25 | assert_equal html, expected_html
26 | end
27 |
28 | def test_it_outputs_div_elements_in_series
29 | expected_html = "" * 2
30 |
31 | html = Webpacker::Svelte::Component.new(@component[:name])
32 | .render(@component[:props])
33 |
34 | html += Webpacker::Svelte::Component.new(@component[:name])
35 | .render(@component[:props])
36 |
37 | assert_equal expected_html, html
38 | end
39 |
40 | def test_it_accepts_html_options
41 | html = Webpacker::Svelte::Component.new(@component[:name])
42 | .render(
43 | @component[:props],
44 | class: "class",
45 | id: "id"
46 | )
47 |
48 | assert(
49 | html.include?('class="class"') && html.include?('id="id"'),
50 | "it includes HTML options"
51 | )
52 | end
53 |
54 | def test_it_accepts_tag_option
55 | html = Webpacker::Svelte::Component.new(@component[:name])
56 | .render(
57 | @component[:props],
58 | tag: "span"
59 | )
60 |
61 | assert(
62 | html.include?(" onMount())
76 | } else if ('addEventListener' in window) {
77 | document.addEventListener('DOMContentLoaded', onMount)
78 | } else {
79 | // add support to IE8 without jQuery
80 | window.attachEvent('onload', onMount)
81 | }
82 | }
83 | }
84 |
85 | export default ujs
86 |
--------------------------------------------------------------------------------
/.rubocop.yml:
--------------------------------------------------------------------------------
1 | AllCops:
2 | TargetRubyVersion: 2.3
3 | # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop
4 | # to ignore them, so only the ones explicitly set in this file are enabled.
5 | DisabledByDefault: true
6 | Exclude:
7 | - '**/node_modules/**/*'
8 | - '**/vendor/**/*'
9 |
10 | # Prefer &&/|| over and/or.
11 | Style/AndOr:
12 | Enabled: true
13 |
14 | # Do not use braces for hash literals when they are the last argument of a
15 | # method call.
16 | Style/BracesAroundHashParameters:
17 | Enabled: true
18 |
19 | # Align `when` with `case`.
20 | Layout/CaseIndentation:
21 | Enabled: true
22 |
23 | # Align comments with method definitions.
24 | Layout/CommentIndentation:
25 | Enabled: true
26 |
27 | # No extra empty lines.
28 | Layout/EmptyLines:
29 | Enabled: true
30 |
31 | # In a regular class definition, no empty lines around the body.
32 | Layout/EmptyLinesAroundClassBody:
33 | Enabled: true
34 |
35 | # In a regular module definition, no empty lines around the body.
36 | Layout/EmptyLinesAroundModuleBody:
37 | Enabled: true
38 |
39 | # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }.
40 | Style/HashSyntax:
41 | Enabled: true
42 |
43 | # Method definitions after `private` or `protected` isolated calls need one
44 | # extra level of indentation.
45 | Layout/IndentationConsistency:
46 | Enabled: true
47 | EnforcedStyle: indented_internal_methods
48 |
49 | # Two spaces, no tabs (for indentation).
50 | Layout/IndentationWidth:
51 | Enabled: true
52 |
53 | Layout/SpaceAfterColon:
54 | Enabled: true
55 |
56 | Layout/SpaceAfterComma:
57 | Enabled: true
58 |
59 | Layout/SpaceAroundEqualsInParameterDefault:
60 | Enabled: true
61 |
62 | Layout/SpaceAroundKeyword:
63 | Enabled: true
64 |
65 | Layout/SpaceAroundOperators:
66 | Enabled: true
67 |
68 | Layout/SpaceBeforeFirstArg:
69 | Enabled: true
70 |
71 | # Defining a method with parameters needs parentheses.
72 | Style/MethodDefParentheses:
73 | Enabled: true
74 |
75 | # Use `foo {}` not `foo{}`.
76 | Layout/SpaceBeforeBlockBraces:
77 | Enabled: true
78 |
79 | # Use `foo { bar }` not `foo {bar}`.
80 | Layout/SpaceInsideBlockBraces:
81 | Enabled: true
82 |
83 | # Use `{ a: 1 }` not `{a:1}`.
84 | Layout/SpaceInsideHashLiteralBraces:
85 | Enabled: true
86 |
87 | Layout/SpaceInsideParens:
88 | Enabled: true
89 |
90 | # Check quotes usage according to lint rule below.
91 | Style/StringLiterals:
92 | Enabled: true
93 | EnforcedStyle: double_quotes
94 |
95 | # Detect hard tabs, no hard tabs.
96 | Layout/Tab:
97 | Enabled: true
98 |
99 | # Blank lines should not have any spaces.
100 | Layout/TrailingBlankLines:
101 | Enabled: true
102 |
103 | # No trailing whitespace.
104 | Layout/TrailingWhitespace:
105 | Enabled: true
106 |
107 | # Use quotes for string literals when they are enough.
108 | Style/UnneededPercentQ:
109 | Enabled: true
110 |
111 | # Align `end` with the matching keyword or starting expression except for
112 | # assignments, where it should be aligned with the LHS.
113 | Lint/EndAlignment:
114 | Enabled: true
115 | EnforcedStyleAlignWith: variable
116 |
117 | # Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg.
118 | Lint/RequireParentheses:
119 | Enabled: true
120 |
--------------------------------------------------------------------------------
/test/example_app/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Make javascript_pack_tag lookup digest hash to enable long-term caching
3 | config.x.webpacker[:digesting] = true
4 |
5 | # Settings specified here will take precedence over those in config/application.rb.
6 |
7 | # Code is not reloaded between requests.
8 | config.cache_classes = true
9 |
10 | # Eager load code on boot. This eager loads most of Rails and
11 | # your application in memory, allowing both threaded web servers
12 | # and those relying on copy on write to perform better.
13 | # Rake tasks automatically ignore this option for performance.
14 | config.eager_load = true
15 |
16 | # Full error reports are disabled and caching is turned on.
17 | config.consider_all_requests_local = false
18 | config.action_controller.perform_caching = true
19 |
20 | # Disable serving static files from the `/public` folder by default since
21 | # Apache or NGINX already handles this.
22 | config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
23 |
24 | # Compress JavaScripts and CSS.
25 | config.assets.js_compressor = :uglifier
26 | # config.assets.css_compressor = :sass
27 |
28 | # Do not fallback to assets pipeline if a precompiled asset is missed.
29 | config.assets.compile = false
30 |
31 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
32 |
33 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
34 | # config.action_controller.asset_host = 'http://assets.example.com'
35 |
36 | # Specifies the header that your server uses for sending files.
37 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
38 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
39 |
40 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
41 | # config.force_ssl = true
42 |
43 | # Use the lowest log level to ensure availability of diagnostic information
44 | # when problems arise.
45 | config.log_level = :debug
46 |
47 | # Prepend all log lines with the following tags.
48 | config.log_tags = [ :request_id ]
49 |
50 | # Use a different cache store in production.
51 | # config.cache_store = :mem_cache_store
52 |
53 | # Use a real queuing backend for Active Job (and separate queues per environment)
54 | # config.active_job.queue_adapter = :resque
55 | # config.active_job.queue_name_prefix = "webpacker-svelte-example_#{Rails.env}"
56 |
57 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
58 | # the I18n.default_locale when a translation cannot be found).
59 | config.i18n.fallbacks = true
60 |
61 | # Send deprecation notices to registered listeners.
62 | config.active_support.deprecation = :notify
63 |
64 | # Use default logging formatter so that PID and timestamp are not suppressed.
65 | config.log_formatter = ::Logger::Formatter.new
66 |
67 | # Use a different logger for distributed setups.
68 | # require 'syslog/logger'
69 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
70 |
71 | if ENV["RAILS_LOG_TO_STDOUT"].present?
72 | logger = ActiveSupport::Logger.new(STDOUT)
73 | logger.formatter = config.log_formatter
74 | config.logger = ActiveSupport::TaggedLogging.new(logger)
75 | end
76 | end
77 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project maintainer at will.ockelmann.wagner@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
75 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: .
3 | specs:
4 | webpacker-svelte (1.0.0)
5 | webpacker
6 |
7 | GEM
8 | remote: https://rubygems.org/
9 | specs:
10 | actioncable (5.2.3)
11 | actionpack (= 5.2.3)
12 | nio4r (~> 2.0)
13 | websocket-driver (>= 0.6.1)
14 | actionmailer (5.2.3)
15 | actionpack (= 5.2.3)
16 | actionview (= 5.2.3)
17 | activejob (= 5.2.3)
18 | mail (~> 2.5, >= 2.5.4)
19 | rails-dom-testing (~> 2.0)
20 | actionpack (5.2.3)
21 | actionview (= 5.2.3)
22 | activesupport (= 5.2.3)
23 | rack (~> 2.0)
24 | rack-test (>= 0.6.3)
25 | rails-dom-testing (~> 2.0)
26 | rails-html-sanitizer (~> 1.0, >= 1.0.2)
27 | actionview (5.2.3)
28 | activesupport (= 5.2.3)
29 | builder (~> 3.1)
30 | erubi (~> 1.4)
31 | rails-dom-testing (~> 2.0)
32 | rails-html-sanitizer (~> 1.0, >= 1.0.3)
33 | activejob (5.2.3)
34 | activesupport (= 5.2.3)
35 | globalid (>= 0.3.6)
36 | activemodel (5.2.3)
37 | activesupport (= 5.2.3)
38 | activerecord (5.2.3)
39 | activemodel (= 5.2.3)
40 | activesupport (= 5.2.3)
41 | arel (>= 9.0)
42 | activestorage (5.2.3)
43 | actionpack (= 5.2.3)
44 | activerecord (= 5.2.3)
45 | marcel (~> 0.3.1)
46 | activesupport (5.2.3)
47 | concurrent-ruby (~> 1.0, >= 1.0.2)
48 | i18n (>= 0.7, < 2)
49 | minitest (~> 5.1)
50 | tzinfo (~> 1.1)
51 | addressable (2.6.0)
52 | public_suffix (>= 2.0.2, < 4.0)
53 | arel (9.0.0)
54 | ast (2.4.0)
55 | builder (3.2.3)
56 | capybara (3.25.0)
57 | addressable
58 | mini_mime (>= 0.1.3)
59 | nokogiri (~> 1.8)
60 | rack (>= 1.6.0)
61 | rack-test (>= 0.6.3)
62 | regexp_parser (~> 1.5)
63 | xpath (~> 3.2)
64 | childprocess (1.0.1)
65 | rake (< 13.0)
66 | concurrent-ruby (1.1.5)
67 | crass (1.0.4)
68 | erubi (1.8.0)
69 | globalid (0.4.2)
70 | activesupport (>= 4.2.0)
71 | i18n (1.6.0)
72 | concurrent-ruby (~> 1.0)
73 | jaro_winkler (1.5.3)
74 | loofah (2.2.3)
75 | crass (~> 1.0.2)
76 | nokogiri (>= 1.5.9)
77 | mail (2.7.1)
78 | mini_mime (>= 0.1.1)
79 | marcel (0.3.3)
80 | mimemagic (~> 0.3.2)
81 | method_source (0.9.2)
82 | mimemagic (0.3.3)
83 | mini_mime (1.0.2)
84 | mini_portile2 (2.4.0)
85 | minitest (5.11.3)
86 | nio4r (2.4.0)
87 | nokogiri (1.10.3)
88 | mini_portile2 (~> 2.4.0)
89 | parallel (1.17.0)
90 | parser (2.6.3.0)
91 | ast (~> 2.4.0)
92 | public_suffix (3.1.1)
93 | puma (4.0.0)
94 | nio4r (~> 2.0)
95 | rack (2.0.7)
96 | rack-proxy (0.6.5)
97 | rack
98 | rack-test (1.1.0)
99 | rack (>= 1.0, < 3)
100 | rails (5.2.3)
101 | actioncable (= 5.2.3)
102 | actionmailer (= 5.2.3)
103 | actionpack (= 5.2.3)
104 | actionview (= 5.2.3)
105 | activejob (= 5.2.3)
106 | activemodel (= 5.2.3)
107 | activerecord (= 5.2.3)
108 | activestorage (= 5.2.3)
109 | activesupport (= 5.2.3)
110 | bundler (>= 1.3.0)
111 | railties (= 5.2.3)
112 | sprockets-rails (>= 2.0.0)
113 | rails-dom-testing (2.0.3)
114 | activesupport (>= 4.2.0)
115 | nokogiri (>= 1.6)
116 | rails-html-sanitizer (1.0.4)
117 | loofah (~> 2.2, >= 2.2.2)
118 | railties (5.2.3)
119 | actionpack (= 5.2.3)
120 | activesupport (= 5.2.3)
121 | method_source
122 | rake (>= 0.8.7)
123 | thor (>= 0.19.0, < 2.0)
124 | rainbow (3.0.0)
125 | rake (12.3.2)
126 | regexp_parser (1.5.1)
127 | rubocop (0.72.0)
128 | jaro_winkler (~> 1.5.1)
129 | parallel (~> 1.10)
130 | parser (>= 2.6)
131 | rainbow (>= 2.2.2, < 4.0)
132 | ruby-progressbar (~> 1.7)
133 | unicode-display_width (>= 1.4.0, < 1.7)
134 | ruby-progressbar (1.10.1)
135 | rubyzip (1.2.3)
136 | selenium-webdriver (3.142.3)
137 | childprocess (>= 0.5, < 2.0)
138 | rubyzip (~> 1.2, >= 1.2.2)
139 | sprockets (3.7.2)
140 | concurrent-ruby (~> 1.0)
141 | rack (> 1, < 3)
142 | sprockets-rails (3.2.1)
143 | actionpack (>= 4.0)
144 | activesupport (>= 4.0)
145 | sprockets (>= 3.0.0)
146 | thor (0.20.3)
147 | thread_safe (0.3.6)
148 | tzinfo (1.2.5)
149 | thread_safe (~> 0.1)
150 | unicode-display_width (1.6.0)
151 | webpacker (4.0.7)
152 | activesupport (>= 4.2)
153 | rack-proxy (>= 0.6.1)
154 | railties (>= 4.2)
155 | websocket-driver (0.7.1)
156 | websocket-extensions (>= 0.1.0)
157 | websocket-extensions (0.1.4)
158 | xpath (3.2.0)
159 | nokogiri (~> 1.8)
160 |
161 | PLATFORMS
162 | ruby
163 |
164 | DEPENDENCIES
165 | bundler (~> 1.13)
166 | capybara
167 | minitest (~> 5.0)
168 | puma (~> 4.0)
169 | rails (~> 5.2.0)
170 | rake (~> 12.0)
171 | rubocop (>= 0.47)
172 | selenium-webdriver
173 | webpacker (~> 4.0.0)
174 | webpacker-svelte!
175 |
176 | BUNDLED WITH
177 | 1.17.2
178 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Webpacker-Svelte
2 |
3 | Webpacker-Svelte makes it easy to use [Svelte](https://svelte.dev) with [Webpacker](https://github.com/rails/webpacker) in your Rails applications.
4 |
5 | [](https://rubygems.org/gems/webpacker-svelte)
6 | [](https://www.npmjs.com/package/webpacker-svelte)
7 | [](https://circleci.com/gh/will-wow/webpacker-svelte)
8 |
9 | This is a port of [@renchap](https://github.com/renchap)'s excellent [webpacker-react](https://github.com/renchap/webpacker-react).
10 |
11 | It supports Webpacker 1.2+.
12 |
13 | An example application is available: https://github.com/will-wow/contacts
14 |
15 | For more information, see the [blog post](https://blog.carbonfive.com/2019/10/29/the-best-of-both-worlds-html-apps-svelte).
16 |
17 | ## Installation
18 |
19 | Your Rails application needs to use Webpacker and have the Svelte integration done. Please refer to their documentation documentation for this: https://github.com/rails/webpacker/blob/master/README.md#svelte
20 |
21 | First, you need to add the [webpacker-svelte](https://rubygems.org/gems/webpacker-svelte) gem to your Rails app Gemfile:
22 |
23 | ```ruby
24 | gem 'webpacker-svelte', "~> 1.0.0"
25 | ```
26 |
27 | Once done, run `bundle` to install the gem.
28 |
29 | Then you need to update your `package.json` file to include the `webpacker-svelte` NPM module:
30 |
31 | ```bash
32 | npm i webpacker-svelte
33 | # Or
34 | yarn add webpacker-svelte
35 | ```
36 |
37 | You are now all set!
38 |
39 | ### Note about versions
40 |
41 | Webpacker-Svelte contains two parts: a Javascript module and a Ruby gem. Both of those components respect [semantic versioning](http://semver.org). **When upgrading the gem, you need to upgrade the NPM module to the same minor version**. New patch versions can be released for each of the two independently, so it is ok to have the NPM module at version `A.X.Y` and the gem at version `A.X.Z`, but you should never have a different `A` or `X`.
42 |
43 | ## Usage
44 |
45 | The first step is to register your root components (those you want to load from your HTML).
46 | In your pack file (`app/javascript/packs/*.js`), import your components as well as `webpacker-svelte` and register them. Considering you have a component in `app/javascript/components/hello.js`:
47 |
48 | ```javascript
49 | import Hello from "components/hello.svelte";
50 | import WebpackerSvelte from "webpacker-svelte";
51 |
52 | WebpackerSvelte.setup({ Hello }); // ES6 shorthand for {Hello: Hello}
53 | ```
54 |
55 | ### With Turbolinks
56 |
57 | You have to make sure Turbolinks is loaded before calling `WebpackerSvelte.initialize()`.
58 |
59 | For example:
60 |
61 | ```javascript
62 | import Hello from "components/hello.svelte";
63 | import WebpackerSvelte from "webpacker-svelte";
64 | import Turbolinks from "turbolinks";
65 |
66 | Turbolinks.start();
67 |
68 | WebpackerSvelte.setup({ Hello });
69 | ```
70 |
71 | You may also load turbolinks in regular asset pipeline `application.js`:
72 |
73 | ```javascript
74 | //= require "turbolinks"
75 | ```
76 |
77 | In that case, make sure your packs are loaded _after_ `application.js`
78 |
79 | Now you can render Svelte components from your views or your controllers.
80 |
81 | ### Rendering from a view
82 |
83 | Use the `svelte_component` helper. The first argument is your component's name, the second one is the `props`:
84 |
85 | ```erb
86 | <%= svelte_component('Hello', name: 'Svelte') %>
87 | ```
88 |
89 | You can pass a `tag` argument to render the Svelte component in another tag than the default `div`. All other arguments will be passed to `content_tag`:
90 |
91 | ```erb
92 | <%= svelte_component('Hello', { name: 'Svelte' }, tag: :span, class: 'my-custom-component') %>
93 | # This will render
94 | ```
95 |
96 | ### Rendering from a controller
97 |
98 | ```rb
99 | class PageController < ApplicationController
100 | def main
101 | render svelte_component: 'Hello', props: { name: 'Svelte' }
102 | end
103 | end
104 | ```
105 |
106 | You can use the `tag_options` argument to change the generated HTML, similar to the `svelte_component` method above:
107 |
108 | ```rb
109 | render svelte_component: 'Hello', props: { name: 'Svelte' }, tag_options: { tag: :span, class: 'my-custom-component' }
110 | ```
111 |
112 | You can also pass any of the usual arguments to `render` in this call: `layout`, `status`, `content_type`, etc.
113 |
114 | _Note: you need to have [Webpack process your code](https://github.com/rails/webpacker#binstubs) before it is available to the browser, either by manually running `./bin/webpack` or having the `./bin/webpack-watcher` process running._
115 |
116 | ### Hot Module Replacement
117 |
118 | **HMR may be working for Svelte3 now, but I haven't tested it. See: https://github.com/sveltejs/svelte-loader/issues/92**
119 |
120 | [HMR](https://webpack.js.org/concepts/hot-module-replacement/) allows to reload / add / remove modules live in the browser without
121 | reloading the page. This allows any change you make to your Svelte components to be applied as soon as you save,
122 | preserving their current state.
123 |
124 | **Once svelte-loader supports HMR for Svelte 3:**
125 |
126 | 1. Set up the webpack svelte loader `svelte` for HMR.
127 |
128 | ```javascript
129 | module.exports = {
130 | test: /\.svelte$/,
131 | use: [
132 | {
133 | loader: "svelte-loader",
134 | options: {
135 | // HMR isn't supported for Svelte3 yet
136 | // https://github.com/sveltejs/svelte-loader/issues/74
137 | hotReload: false
138 | // Emit css that webpacker can extract into a separate css file in production.
139 | emitCss: true
140 | }
141 | }
142 | ]
143 | };
144 | ```
145 |
146 | 1. Set up `webpack-dev-server` for HMR. This is easy, just switch `hmr: true` in your `webpacker.yml` for development!
147 |
148 | 1. you now need to use `webpack-dev-server` (in place of `webpack` or `webpack-watcher`).
149 |
150 | ## Development
151 |
152 | To work on this gem locally, may want to clone and setup [the example application](https://github.com/will-wow/contacts).
153 |
154 | Then you need to change the example app Gemfile to point to your local repository and run bundle afterwards:
155 |
156 | ```ruby
157 | gem 'webpacker-svelte', path: '~/code/webpacker-svelte/'
158 | ```
159 |
160 | Finally, you need to tell Yarn to use your local copy of the NPM module in this application, using [`yarn link`](https://yarnpkg.com/en/docs/cli/link):
161 |
162 | ```bash
163 | $ cd /path/to/webpacker-svelte/javascript/webpacker_svelte-npm-module/
164 | $ yarn install
165 | $ yarn build # compiles the code from src/ to dist/
166 | $ yarn link
167 | success Registered "webpacker-svelte".
168 | info You can now run `yarn link "webpacker-svelte"` in the projects where you want to use this module and it will be used instead.
169 | $ cd /path/to/contacts/
170 | $ yarn link webpacker-svelte
171 | success Registered "webpacker-svelte".
172 | $ yarn install
173 | ```
174 |
175 | After launching `./bin/webpack-watcher` and `./bin/rails server` in your example app directory, you can now change the Ruby or Javascript code in your local `webpacker-svelte` repository, and test it immediately using the example app.
176 |
177 | ## Testing
178 |
179 | If you changed the local javascript package, first ensure it is built (see above).
180 |
181 | You'll have to install chromedriver to run the tests:
182 |
183 | ```bash
184 | $ brew install --cask chromedriver
185 | # Or
186 | $ npm install -g chromedriver
187 | ```
188 |
189 | To run the test suite:
190 |
191 | ```sh
192 | $ bundle execute rake test
193 | ```
194 |
195 | If you change the javascript code, please ensure there are no style errors before committing:
196 |
197 | ```sh
198 | $ cd javascript/webpacker_svelte-npm-module/
199 | $ yarn lint
200 | ```
201 |
202 | ## Contributing
203 |
204 | Bug reports and pull requests are welcome on GitHub at https://github.com/will-wow/webpacker-svelte.
205 | Please feel free to open issues about your needs and features you would like to be added.
206 |
207 | ### Thanks
208 |
209 | All credit to [@renchap](https://github.com/renchap) for [webpacker-react](https://github.com/renchap/webpacker-react), this is just a light re-write of that repo to support Svelte!
210 |
--------------------------------------------------------------------------------