Packages

Inelegantly replace Brunch with Webpack

Current section

Files

Jump to
phoenix_gen_webpack lib webpack.ex
Raw

lib/webpack.ex

defmodule Mix.Tasks.Phoenix.Gen.Webpack do
use Mix.Task
@package_json_template Path.join(__DIR__, "templates/package.json")
@webpack_config_template Path.join(__DIR__, "templates/webpack.config.js")
@require_js_matcher ~r|\s*<script>require\("web\/static\/js\/app"\)<\/script>\n|
@require_css_matcher ~r|\s*<link rel="stylesheet" href="<%= static_path\(@conn, "\/css\/app\.css"\) %>">\n|
@brunch_watcher_matcher ~r|watchers: \[(.*?)\]\n|
@webpack_watcher ~s|watchers: [{Path.expand("node_modules/webpack/bin/webpack.js"), ["--watch", "--colors"]}]\n|
@shortdoc "Inelegantly replace Brunch with Webpack"
@doc """
Removes Brunch configuration files (if they exist)
and replaces them with a basic Webpack configuration.
"""
def run(_args) do
replace_package_json!
clean_node_modules!
clean_priv_static!
create_webpack_config!
remove_undefined_requires_in_layout!
create_static_files!
prefix_app_scss_to_app_js!
add_webpack_to_watchers_list!
done!
end
defp replace_package_json! do
print("Replacing package.json..")
File.rm_rf! "package.json"
File.cp! @package_json_template, "package.json"
end
defp clean_node_modules! do
print("Cleaning node_modules..")
File.rm_rf! "node_modules"
end
defp clean_priv_static! do
print("Cleaning priv/static..")
File.rm_rf! "priv/static/css"
File.rm_rf! "priv/static/js"
File.mkdir_p! "priv/static/js"
end
defp create_webpack_config! do
print("Replacing brunch-config.js with webpack.config.js..")
File.rm_rf! "brunch-config.js"
File.cp! @webpack_config_template, "webpack.config.js"
end
defp remove_undefined_requires_in_layout! do
print("Removing Brunch requires from templates.layout/app.html.eex..")
File.read!("web/templates/layout/app.html.eex")
|> String.replace(@require_js_matcher, "", global: false)
|> String.replace(@require_css_matcher, "", global: false)
|> (&File.write!("web/templates/layout/app.html.eex", &1)).()
end
defp create_static_files! do
print("Creating static files..")
File.mkdir_p! "web/static/css"
File.mkdir_p! "web/static/js"
File.touch! "web/static/css/app.scss"
File.touch! "web/static/js/app.js"
end
defp prefix_app_scss_to_app_js! do
print("Prefixing Webpack entry file with main SCSS file path..")
js = File.read! "web/static/js/app.js"
output = ~s|import "../css/app.scss"\n| <> js
File.write! "web/static/js/app.js", output
end
defp add_webpack_to_watchers_list! do
print("Setting Webpack as a watcher..")
File.read!("config/dev.exs")
|> String.replace(@brunch_watcher_matcher, @webpack_watcher, global: false)
|> (&File.write!("config/dev.exs", &1)).()
end
defp done! do
print("ALL DONE!")
end
defp print(message) do
Mix.shell.info [:green, message]
end
end