Inertia with Vue
Rails template for Inertia with Vue
Used 35 times
S
SlimShady
Usage
Script that scaffolds Inertia with Vue. Tested on a fresh Rails 6.0.3.3 install.
Remember to commit your changes before running the script in case something goes wrong and you have to rollback.
What it does:
Remember to commit your changes before running the script in case something goes wrong and you have to rollback.
What it does:
- Adds 'inertia_rails' gem
- Installs Vue using webpacker
- Installs npm dependencies using yarn
- Creates inertia.js config file and imports it in application.js
- Creates Pages and Shared directories
- Creates a sample component called Hello.Vue
Remember to add a correct javascript_pack_tag (with defer: true):
<%= javascript_pack_tag 'application', defer: true %>
You can check if everything works properly with this controller method:
def show render inertia: 'Hello', props: { greeting: 'Bonjour' } end
Run this command in your Rails app directory in the terminal:
rails app:template LOCATION="https://railsbytes.com/script/XnJsE5"
Template Source
Review the code before running this template on your machine.
require 'fileutils'
def do_bundle
# Custom bundle command ensures dependencies are correctly installed
Bundler.with_unbundled_env { run 'bundle install' }
end
def config_inertia_vue
create_inertia_vue_file
import_inertia
create_hello_inertia_file
create_shared_folder
delete_hello_vue_file
delete_example_app_vue_file
end
def create_inertia_vue_file
contents = <<~HEREDOC
import { App, plugin } from '@inertiajs/inertia-vue'
import Vue from 'vue'
Vue.use(plugin)
const app = document.getElementById('app')
new Vue({
render: h => h(App, {
props: {
initialPage: JSON.parse(app.dataset.page),
resolveComponent: name => require(`../Pages/${name}`).default,
},
}),
}).$mount(app)
HEREDOC
File.open('./app/javascript/packs/inertia.js', 'w') { |f| f.write(contents) }
end
def import_inertia
File.open('./app/javascript/packs/application.js', 'a') { |f| f.write("import './inertia.js'") }
end
def create_hello_inertia_file
contents = <<~HEREDOCS
<template>
<div>{{ greeting }} Inertia!</div>
</template>
<script>
export default {
props: {
greeting: {
default: "Hello",
},
},
};
</script>
HEREDOCS
path = './app/javascript/Pages'
FileUtils.mkdir(path) unless Dir.exist?(path)
File.open("#{path}/Hello.vue", 'w') { |f| f.write(contents) }
end
def create_shared_folder
path = './app/javascript/Shared'
FileUtils.mkdir(path) unless Dir.exist?(path)
end
def delete_hello_vue_file
file_path = './app/javascript/packs/hello_vue.js'
File.delete(file_path) if File.exist? file_path
end
def delete_example_app_vue_file
file_path = './app/javascript/app.vue'
File.delete(file_path) if File.exist? file_path
end
gem 'inertia_rails'
gem 'webpacker' unless defined?(Webpacker)
do_bundle
run 'rails webpacker:install'
run 'rails webpacker:install:vue'
run 'yarn add @inertiajs/inertia @inertiajs/inertia-vue'
config_inertia_vue