Skip to content

Commit

Permalink
Add Bun support (#167)
Browse files Browse the repository at this point in the history
* Add Bun support

* Tweak README

* Tweak README for clarity
  • Loading branch information
terracatta authored Sep 11, 2023
1 parent a6964f3 commit e308e76
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 26 deletions.
21 changes: 13 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
# JavaScript Bundling for Rails

Use [esbuild](https://esbuild.github.io), [rollup.js](https://rollupjs.org), or [Webpack](https://webpack.js.org) to bundle your JavaScript, then deliver it via the asset pipeline in Rails. This gem provides installers to get you going with the bundler of your choice in a new Rails application, and a convention to use `app/assets/builds` to hold your bundled output as artifacts that are not checked into source control (the installer adds this directory to `.gitignore` by default).
Use [Bun](https://bun.sh), [esbuild](https://esbuild.github.io), [rollup.js](https://rollupjs.org), or [Webpack](https://webpack.js.org) to bundle your JavaScript, then deliver it via the asset pipeline in Rails. This gem provides installers to get you going with the bundler of your choice in a new Rails application, and a convention to use `app/assets/builds` to hold your bundled output as artifacts that are not checked into source control (the installer adds this directory to `.gitignore` by default).

You develop using this approach by running the bundler in watch mode in a terminal with `yarn build --watch` (and your Rails server in another, if you're not using something like [puma-dev](https://github.com/puma/puma-dev)). You can also use `./bin/dev`, which will start both the Rails server and the JS build watcher (along with a CSS build watcher, if you're also using `cssbundling-rails`).

Whenever the bundler detects changes to any of the JavaScript files in your project, it'll bundle `app/javascript/application.js` into `app/assets/builds/application.js` (and all other entry points configured). You can refer to the build output in your layout using the standard asset pipeline approach with `<%= javascript_include_tag "application", defer: true %>`.

When you deploy your application to production, the `javascript:build` task attaches to the `assets:precompile` task to ensure that all your package dependencies from `package.json` have been installed via yarn, and then runs `yarn build` to process all the entry points, as it would in development. The latter files are then picked up by the asset pipeline, digested, and copied into public/assets, as any other asset pipeline file.
When you deploy your application to production, the `javascript:build` task attaches to the `assets:precompile` task to ensure that all your package dependencies from `package.json` have been installed via your javascript package manager (bun or yarn), and then runs the build script defined in `package.json` to process all the entry points, as it would in development. The latter files are then picked up by the asset pipeline, digested, and copied into public/assets, as any other asset pipeline file.

This also happens in testing where the bundler attaches to the `test:prepare` task to ensure the JavaScript has been bundled before testing commences. If your testing library of choice does not call the `test:prepare` Rake task, ensure that your test suite runs `javascript:build` to bundle JavaScript before testing commences.

That's it!

You can configure your bundler options in the `build` script in `package.json` or via the installer-generated `rollup.config.js` for rollup.js or `webpack.config.json` for Webpack (esbuild does not have a default configuration format, and we don't intend to use esbuild as an API in order to hack around it).
You can configure your bundler options in the `build` script in `package.json` or via the installer-generated `bun.config.js` for Bun, `rollup.config.js` for rollup.js or `webpack.config.json` for Webpack (esbuild does not have a default configuration format, and we don't intend to use esbuild as an API in order to hack around it).

If you're already using [`webpacker`](https://github.com/rails/webpacker) and you're wondering if you should migrate to `jsbundling-rails`, have a look at [the high-level comparison](./docs/comparison_with_webpacker.md). If you're looking to migrate from webpacker, see the [migration guide](https://github.com/rails/jsbundling-rails/blob/main/docs/switch_from_webpacker.md).

If you want to use webpack features like [code splitting](https://webpack.js.org/guides/code-splitting/) and [hot module reloading](https://webpack.js.org/concepts/hot-module-replacement/), consider using the official fork of `webpacker`, [`shakapacker`](https://github.com/shakacode/shakapacker).

## Installation
If you are installing esbuild, rollup, or webpack, you must already have node
and yarn installed on your system. You will also need npx version 7.1.0 or later.

You must already have node and yarn installed on your system. You will also need npx version 7.1.0 or later. Then run:
If you are using Bun, then you must have the Bun runtime already installed on
your system.

To get started run:

```
./bin/bundle add jsbundling-rails
```

```
./bin/rails javascript:install:[esbuild|rollup|webpack]
./bin/rails javascript:install:[bun|esbuild|rollup|webpack]
```

Or, in Rails 7+, you can preconfigure your new application to use a specific bundler with `rails new myapp -j [esbuild|rollup|webpack]`.
Or, in Rails 7+, you can preconfigure your new application to use a specific bundler with `rails new myapp -j [bun|esbuild|rollup|webpack]`.


## FAQ
Expand All @@ -39,9 +44,9 @@ Or, in Rails 7+, you can preconfigure your new application to use a specific bun

The default build script for esbuild relies on the `app/javascript/*.*` glob pattern to compile multiple entrypoints automatically. This glob pattern is not available by default on Windows, so you need to change the build script in `package.json` to manually list the entrypoints you wish to compile.

### Why does esbuild overwrite my application.css?
### Why does bun/esbuild overwrite my application.css?

If you [import CSS](https://esbuild.github.io/content-types/#css-from-js) in your application.js while using esbuild, you'll be creating both an `app/assets/builds/application.js` _and_ `app/assets/builds/application.css` file when bundling. The latter can conflict with the `app/assets/builds/application.css` produced by [cssbundling-rails](https://github.com/rails/cssbundling-rails). The solution is to either change the output file for esbuild (and the references for that) or for cssbundling. Both are specified in `package.json`.
If you [import CSS](https://esbuild.github.io/content-types/#css-from-js) in your application.js while using esbuild or Bun, you'll be creating both an `app/assets/builds/application.js` _and_ `app/assets/builds/application.css` file when bundling. The latter can conflict with the `app/assets/builds/application.css` produced by [cssbundling-rails](https://github.com/rails/cssbundling-rails). The solution is to either change the output file for bun/esbuild (and the references for that) or for cssbundling. Both are specified in `package.json`.

### How can I reference static assets in JavaScript code?

Expand Down
2 changes: 2 additions & 0 deletions lib/install/bun/Procfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
web: env RUBY_DEBUG_OPEN=true bin/rails server
js: bun run build --watch
37 changes: 37 additions & 0 deletions lib/install/bun/bun.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import path from 'path';
import fs from 'fs';

const config = {
sourcemap: "external",
entrypoints: ["app/javascript/application.js"],
outdir: path.join(process.cwd(), "app/assets/builds"),
};

const build = async (config) => {
const result = await Bun.build(config);

if (!result.success) {
if (process.argv.includes('--watch')) {
console.error("Build failed");
for (const message of result.logs) {
console.error(message);
}
return;
} else {
throw new AggregateError(result.logs, "Build failed");
}
}
};

(async () => {
await build(config);

if (process.argv.includes('--watch')) {
fs.watch(path.join(process.cwd(), "app/javascript"), { recursive: true }, (eventType, filename) => {
console.log(`File changed: ${filename}. Rebuilding...`);
build(config);
});
} else {
process.exit(0);
}
})();
20 changes: 20 additions & 0 deletions lib/install/bun/install.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require 'json'

if Rails.root.join("Procfile.dev").exist?
append_to_file "Procfile.dev", "js: bun build --watch\n"
else
say "Add default Procfile.dev"
copy_file "#{__dir__}/Procfile.dev", "Procfile.dev"

say "Ensure foreman is installed"
run "gem install foreman"
end

say "Add default bun.config.js"
copy_file "#{__dir__}/bun.config.js", "bun.config.js"

say "Add build script to package.json"
package_json = JSON.parse(File.read("package.json"))
package_json["scripts"] ||= {}
package_json["scripts"]["build"] = "bun bun.config.js"
File.write("package.json", JSON.pretty_generate(package_json))
10 changes: 0 additions & 10 deletions lib/install/install.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,6 @@
copy_file "#{__dir__}/package.json", "package.json"
end

if Rails.root.join("Procfile.dev").exist?
append_to_file "Procfile.dev", "js: yarn build --watch\n"
else
say "Add default Procfile.dev"
copy_file "#{__dir__}/Procfile.dev", "Procfile.dev"

say "Ensure foreman is installed"
run "gem install foreman"
end

say "Add bin/dev to start foreman"
copy_file "#{__dir__}/dev", "bin/dev"
chmod "bin/dev", 0755, verbose: false
9 changes: 9 additions & 0 deletions lib/install/install_node.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
if Rails.root.join("Procfile.dev").exist?
append_to_file "Procfile.dev", "js: yarn build --watch\n"
else
say "Add default Procfile.dev"
copy_file "#{__dir__}/Procfile.dev", "Procfile.dev"

say "Ensure foreman is installed"
run "gem install foreman"
end
29 changes: 24 additions & 5 deletions lib/tasks/jsbundling/build.rake
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
namespace :javascript do
desc "Install JavaScript dependencies"
task :install do
unless system "yarn install"
raise "jsbundling-rails: Command install failed, ensure yarn is installed"
command = install_command
unless system(command)
raise "jsbundling-rails: Command install failed, ensure #{command.split.first} is installed"
end
end

desc "Build your JavaScript bundle"
build_task = task :build do
unless system "yarn build"
raise "jsbundling-rails: Command build failed, ensure `yarn build` runs without errors"
command = build_command
unless system(command)
raise "jsbundling-rails: Command build failed, ensure `#{command}` runs without errors"
end
end
build_task.prereqs << :install unless ENV["SKIP_YARN_INSTALL"]

build_task.prereqs << :install unless ENV["SKIP_YARN_INSTALL"] || ENV["SKIP_BUN_INSTALL"]
end

def install_command
return "bun install" if File.exist?('bun.lockb') || (tool_exists?('bun') && !File.exist?('yarn.lock'))
return "yarn install" if File.exist?('yarn.lock') || tool_exists?('yarn')
raise "jsbundling-rails: No suitable tool found for installing JavaScript dependencies"
end

def build_command
return "bun run build" if File.exist?('bun.lockb') || (tool_exists?('bun') && !File.exist?('yarn.lock'))
return "yarn build" if File.exist?('yarn.lock') || tool_exists?('yarn')
raise "jsbundling-rails: No suitable tool found for building JavaScript"
end

def tool_exists?(tool)
system "command -v #{tool} > /dev/null"
end

unless ENV["SKIP_JS_BUILD"]
Expand Down
16 changes: 13 additions & 3 deletions lib/tasks/jsbundling/install.rake
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,28 @@ namespace :javascript do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/install.rb", __dir__)}"
end

desc "Install node-specific elements for bundlers that use node/yarn."
task :node_shared do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/install_node.rb", __dir__)}"
end

desc "Install Bun"
task bun: "javascript:install:shared" do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/bun/install.rb", __dir__)}"
end

desc "Install esbuild"
task esbuild: "javascript:install:shared" do
task esbuild: ["javascript:install:shared", "javascript:install:node_shared"] do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/esbuild/install.rb", __dir__)}"
end

desc "Install rollup.js"
task rollup: "javascript:install:shared" do
task rollup: ["javascript:install:shared", "javascript:install:node_shared"] do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/rollup/install.rb", __dir__)}"
end

desc "Install Webpack"
task webpack: "javascript:install:shared" do
task webpack: ["javascript:install:shared", "javascript:install:node_shared"] do
system "#{RbConfig.ruby} ./bin/rails app:template LOCATION=#{File.expand_path("../../install/webpack/install.rb", __dir__)}"
end
end
Expand Down

0 comments on commit e308e76

Please sign in to comment.