Skip to content

Commit

Permalink
Convert javascript from sprockets to webpacker
Browse files Browse the repository at this point in the history
  • Loading branch information
swrobel committed May 23, 2017
1 parent f0a1994 commit 04f23e1
Show file tree
Hide file tree
Showing 31 changed files with 5,636 additions and 431 deletions.
12 changes: 12 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": "> 1%",
"uglify": true
},
"useBuiltIns": true
}]
]
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,5 @@

.env*
!invoker.ini
/public/packs
/node_modules
4 changes: 4 additions & 0 deletions .postcssrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
plugins:
postcss-smart-import: {}
precss: {}
autoprefixer: {}
3 changes: 1 addition & 2 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ gem 'friendly_id'
gem 'pg', '~> 0.18'
gem 'puma'
gem 'slim-rails'
gem 'turbolinks'
gem 'uglifier', '>= 1.3.0'
gem 'webpacker', github: 'rails/webpacker'

group :development, :test do
gem 'dotenv-rails'
Expand Down
18 changes: 11 additions & 7 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
GIT
remote: https://github.com/rails/webpacker.git
revision: 158987a82b605b534bcdc9468efca2602313c791
specs:
webpacker (1.2)
activesupport (>= 4.2)
multi_json (~> 1.2)
railties (>= 4.2)

GEM
remote: https://rubygems.org/
specs:
Expand Down Expand Up @@ -118,6 +127,7 @@ GEM
mime-types-data (3.2016.0521)
mini_portile2 (2.1.0)
minitest (5.10.2)
multi_json (1.12.1)
nenv (0.3.0)
newrelic_rpm (4.1.0.333)
nio4r (2.0.0)
Expand Down Expand Up @@ -208,13 +218,8 @@ GEM
thor (0.19.4)
thread_safe (0.3.6)
tilt (2.0.7)
turbolinks (5.0.1)
turbolinks-source (~> 5)
turbolinks-source (5.0.3)
tzinfo (1.2.3)
thread_safe (~> 0.1)
uglifier (3.2.0)
execjs (>= 0.3.0, < 3)
unicode-display_width (1.2.1)
uuid (2.3.8)
macaddr (~> 1.0)
Expand Down Expand Up @@ -250,9 +255,8 @@ DEPENDENCIES
slim-rails
spring
terminal-notifier-guard
turbolinks
uglifier (>= 1.3.0)
web-console (~> 3.0)
webpacker!

RUBY VERSION
ruby 2.4.1p111
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ Pull data from [Surfline](http://www.surfline.com/), [MagicSeaweed](http://magic

1. Install postgres, if you don't have it already: `brew install postgresql`
1. Create your database & seed it with spots: `rake db:setup`
1. Install [Browsersync](https://www.browsersync.io/) if you want livereloading functionality: `npm install -g browser-sync
`
1. Install [yarn](https://yarnpkg.com): `brew install yarn`
1. Install yarn packages: `yarn`
1. Grab some [Spitcast](http://www.spitcast.com/) data: `rake spitcast:update`
1. Grab some [Surfline](http://www.surfline.com/) data: `rake surfline:update`
1. Grab some [MagicSeaweed](http://magicseaweed.com/) data (requires a valid [API key](http://magicseaweed.com/developer/sign-up)): `MSW_API_KEY=xxx rake msw:update`
1. Start the server: `bin/invoker start`
1. Connect to https://surf.dev
1. Score!

Note: If you get a security warning in Chrome, Click "Advanced" and then "Proceed to surf.dev (unsafe)". Nothing to worry about, you're just connecting to your own machine and it's a self-signed SSL certificate so Chrome freaks out.
Note: If you get a security warning in Chrome, Click "Advanced" and then "Proceed to surf.dev (unsafe)". Nothing to worry about, you're just connecting to your own machine and it's a self-signed SSL certificate so Chrome freaks out. You will also probably need to open the [Browsersync javascript](https://surf.dev:9500/browser-sync/browser-sync-client.js) and [Webpacker bundle](https://surf.dev:9001/packs/application.js) once each to trust those certificates as well. I'm hoping to find a better workaround for this in the future...

**Pull requests welcome, especially around new data sources/better data visualization (see [TODO](#todo) for suggestions)**

Expand Down
6 changes: 0 additions & 6 deletions app/assets/javascripts/analytics.js

This file was deleted.

16 changes: 0 additions & 16 deletions app/assets/javascripts/application.js

This file was deleted.

5 changes: 5 additions & 0 deletions app/javascript/packs/application.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const Highcharts = require('highcharts')
window.Highcharts = Highcharts

const Chartkick = require('chartkick')
window.Chartkick = Chartkick
4 changes: 2 additions & 2 deletions app/views/layouts/application.html.slim
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ html
meta property='og:description' content='Pulls data from Surfline, MagicSeaweed &amp; Spitcast APIs to display an aggregated surf forecast.'
meta property='og:image' content= image_url('wave.jpg')

= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
= javascript_include_tag 'application', 'data-turbolinks-track' => true
= stylesheet_link_tag 'application', media: 'all'
= javascript_pack_tag 'application'
- if ENV['GOOGLE_ANALYTICS_ID']
javascript:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
Expand Down
8 changes: 5 additions & 3 deletions bin/spring
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ unless defined?(Spring)
require 'rubygems'
require 'bundler'

if (match = Bundler.default_lockfile.read.match(/^GEM$.*?^ (?: )*spring \((.*?)\)$.*?^$/m))
Gem.paths = { 'GEM_PATH' => [Bundler.bundle_path.to_s, *Gem.path].uniq.join(Gem.path_separator) }
gem 'spring', match[1]
lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
spring = lockfile.specs.detect { |spec| spec.name == "spring" }
if spring
Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
gem 'spring', spring.version
require 'spring/binstub'
end
end
2 changes: 1 addition & 1 deletion bin/update
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ chdir APP_ROOT do

puts '== Installing dependencies =='
system! 'gem install bundler --conservative'
system 'bundle check' or system! 'bundle install'
system('bundle check') || system!('bundle install')

puts "\n== Updating database =="
system! 'bin/rails db:migrate'
Expand Down
28 changes: 28 additions & 0 deletions bin/webpack
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env ruby
$stdout.sync = true

require "shellwords"
require "yaml"

ENV["RAILS_ENV"] ||= "development"
RAILS_ENV = ENV["RAILS_ENV"]

ENV["NODE_ENV"] ||= RAILS_ENV
NODE_ENV = ENV["NODE_ENV"]

APP_PATH = File.expand_path("../", __dir__)
NODE_MODULES_PATH = File.join(APP_PATH, "node_modules")
WEBPACK_CONFIG = File.join(APP_PATH, "config/webpack/#{NODE_ENV}.js")

unless File.exist?(WEBPACK_CONFIG)
puts "Webpack configuration not found."
puts "Please run bundle exec rails webpacker:install to install webpacker"
exit!
end

newenv = { "NODE_PATH" => NODE_MODULES_PATH.shellescape }
cmdline = ["yarn", "run", "webpack", "--", "--config", WEBPACK_CONFIG] + ARGV

Dir.chdir(APP_PATH) do
exec newenv, *cmdline
end
43 changes: 43 additions & 0 deletions bin/webpack-dev-server
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env ruby
$stdout.sync = true

require "shellwords"
require "yaml"

ENV["RAILS_ENV"] ||= "development"
RAILS_ENV = ENV["RAILS_ENV"]

ENV["NODE_ENV"] ||= RAILS_ENV
NODE_ENV = ENV["NODE_ENV"]

APP_PATH = File.expand_path("../", __dir__)
CONFIG_FILE = File.join(APP_PATH, "config/webpacker.yml")
NODE_MODULES_PATH = File.join(APP_PATH, "node_modules")
WEBPACK_CONFIG = File.join(APP_PATH, "config/webpack/development.js")

def args(key)
index = ARGV.index(key)
index ? ARGV[index + 1] : nil
end

begin
dev_server = YAML.load_file(CONFIG_FILE)["development"]["dev_server"]

DEV_SERVER_HOST = "http#{"s" if args('--https') || dev_server["https"]}://#{args('--host') || dev_server["host"]}:#{args('--port') || dev_server["port"]}"

rescue Errno::ENOENT, NoMethodError
puts "Webpack dev_server configuration not found in #{CONFIG_FILE}."
puts "Please run bundle exec rails webpacker:install to install webpacker"
exit!
end

newenv = {
"NODE_PATH" => NODE_MODULES_PATH.shellescape,
"ASSET_HOST" => DEV_SERVER_HOST.shellescape
}.freeze

cmdline = ["yarn", "run", "webpack-dev-server", "--", "--progress", "--color", "--config", WEBPACK_CONFIG] + ARGV

Dir.chdir(APP_PATH) do
exec newenv, *cmdline
end
11 changes: 11 additions & 0 deletions bin/yarn
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env ruby
VENDOR_PATH = File.expand_path('..', __dir__)
Dir.chdir(VENDOR_PATH) do
begin
exec "yarnpkg #{ARGV.join(" ")}"
rescue Errno::ENOENT
$stderr.puts "Yarn executable was not detected in the system."
$stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install"
exit 1
end
end
2 changes: 1 addition & 1 deletion config/environments/production.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass

# Do not fallback to assets pipeline if a precompiled asset is missed.
Expand Down
35 changes: 35 additions & 0 deletions config/webpack/configuration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Common configuration for webpacker loaded from config/webpacker.yml

const { join, resolve } = require('path')
const { env } = require('process')
const { safeLoad } = require('js-yaml')
const { readFileSync } = require('fs')

const configPath = resolve('config', 'webpacker.yml')
const loadersDir = join(__dirname, 'loaders')
const settings = safeLoad(readFileSync(configPath), 'utf8')[env.NODE_ENV]

function removeOuterSlashes(string) {
return string.replace(/^\/*/, '').replace(/\/*$/, '')
}

function formatPublicPath(host = '', path = '') {
let formattedHost = removeOuterSlashes(host)
if (formattedHost && !/^http/i.test(formattedHost)) {
formattedHost = `//${formattedHost}`
}
const formattedPath = removeOuterSlashes(path)
return `${formattedHost}/${formattedPath}/`
}

const output = {
path: resolve('public', settings.public_output_path),
publicPath: formatPublicPath(env.ASSET_HOST, settings.public_output_path)
}

module.exports = {
settings,
env,
loadersDir,
output
}
32 changes: 32 additions & 0 deletions config/webpack/development.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Note: You must restart bin/webpack-dev-server for changes to take effect

const merge = require('webpack-merge')
const sharedConfig = require('./shared.js')
const { settings, output } = require('./configuration.js')

module.exports = merge(sharedConfig, {
devtool: 'cheap-eval-source-map',

stats: {
errorDetails: true
},

output: {
pathinfo: true
},

devServer: {
clientLogLevel: 'none',
https: settings.dev_server.https,
host: settings.dev_server.host,
port: settings.dev_server.port,
contentBase: output.path,
publicPath: output.publicPath,
compress: true,
headers: { 'Access-Control-Allow-Origin': '*' },
historyApiFallback: true,
watchOptions: {
ignored: /node_modules/
}
}
})
12 changes: 12 additions & 0 deletions config/webpack/loaders/assets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { env, publicPath } = require('../configuration.js')

module.exports = {
test: /\.(jpg|jpeg|png|gif|svg|eot|ttf|woff|woff2)$/i,
use: [{
loader: 'file-loader',
options: {
publicPath,
name: env.NODE_ENV === 'production' ? '[name]-[hash].[ext]' : '[name].[ext]'
}
}]
}
5 changes: 5 additions & 0 deletions config/webpack/loaders/babel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
test: /\.js(\.erb)?$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
4 changes: 4 additions & 0 deletions config/webpack/loaders/coffee.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
test: /\.coffee(\.erb)?$/,
loader: 'coffee-loader'
}
9 changes: 9 additions & 0 deletions config/webpack/loaders/erb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
test: /\.erb$/,
enforce: 'pre',
exclude: /node_modules/,
loader: 'rails-erb-loader',
options: {
runner: 'bin/rails runner'
}
}
15 changes: 15 additions & 0 deletions config/webpack/loaders/sass.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const { env } = require('../configuration.js')

module.exports = {
test: /\.(scss|sass|css)$/i,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: env.NODE_ENV === 'production' } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
'resolve-url-loader',
{ loader: 'sass-loader', options: { sourceMap: true } }
]
})
}
21 changes: 21 additions & 0 deletions config/webpack/production.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Note: You must restart bin/webpack-dev-server for changes to take effect

/* eslint global-require: 0 */

const webpack = require('webpack')
const merge = require('webpack-merge')
const CompressionPlugin = require('compression-webpack-plugin')
const sharedConfig = require('./shared.js')

module.exports = merge(sharedConfig, {
output: { filename: '[name]-[chunkhash].js' },

plugins: [
new webpack.optimize.UglifyJsPlugin(),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.(js|css|html|json|ico|svg|eot|otf|ttf)$/
})
]
})
Loading

0 comments on commit 04f23e1

Please sign in to comment.