Skip to content

Commit

Permalink
Update docs & install for referencing images in JS (#158)
Browse files Browse the repository at this point in the history
* asset path should use / so it works on more than just the root routes

* update the image loading instructions so that files are marked  and skipped by sprockets
  • Loading branch information
tgaff committed Jun 18, 2023
1 parent ef5a384 commit ec47a81
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,13 @@ If you [import CSS](https://esbuild.github.io/content-types/#css-from-js) in you
Suppose you have an image `app/javascript/images/example.png` that you need to reference in frontend code built with esbuild.

1. Create the image at `app/javascript/images/example.png`.
1. In `package.json`, under `"scripts"` and `"build"`, add the option `--loader:.png=file` to the esbuild script, which instructs esbuild to copy png files to the build directory.
1. When esbuild runs, it will copy the png file to something like `app/assets/builds/example-5SRKKTLZ.png`.
1. In `package.json`, under `"scripts"` and `"build"`, add the additional arguments:
* `--loader:.png=file` This instructs esbuild to copy png files to the build directory.
* `--asset-names=[name]-[hash].digested` This tells esbuild to append `.digested` to the file name so that sprockets or propshaft will not append an additional digest hash to the file.
1. When esbuild runs, it will copy the png file to something like `app/assets/builds/example-5SRKKTLZ.digested.png`.
1. In frontend code, the image is available for import by its original name: `import Example from "../images/example.png"`.
1. The image itself can now be referenced by its imported name, e.g. in React, `<img src={Example} />`.
1. The path of the image resolves to `/assets/example-5SRKKTLZ.png`, which is served by the asset pipeline.
1. The path of the image resolves to `/assets/example-5SRKKTLZ.digested.png`, which is served by the asset pipeline.

## License

Expand Down
2 changes: 1 addition & 1 deletion lib/install/esbuild/install.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
run "yarn add esbuild"

say "Add build script"
build_script = "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets"
build_script = "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=/assets"

case `npx -v`.to_f
when 7.1...8.0
Expand Down

0 comments on commit ec47a81

Please sign in to comment.