{"_id":"@agney/shakapacker","name":"@agney/shakapacker","dist-tags":{"latest":"6.6.0"},"versions":{"6.6.0":{"name":"@agney/shakapacker","version":"6.6.0","description":"Use webpack to manage app-like JavaScript modules in Rails","main":"package/index.js","engines":{"node":"^12.13.0 || ^14 || >=16","yarn":">=1 <4"},"peerDependencies":{"@babel/core":"^7.17.9","@babel/plugin-transform-runtime":"^7.17.0","@babel/preset-env":"^7.16.11","@babel/runtime":"^7.17.9","@rspack/core":"^1.2.6","babel-loader":"^8.2.4 || ^9.0.0","compression-webpack-plugin":"^9.0.0 || ^10.0.0","terser-webpack-plugin":"^5.3.1","webpack":"^5.72.0","webpack-cli":"^4.9.2 || ^5.0.0","webpack-dev-server":"^4.9.0","webpack-merge":"^5.8.0"},"dependencies":{"@rspack/core":"^1.2.6","glob":"^7.2.0","js-yaml":"^4.1.0","path-complete-extname":"^1.0.0","rspack-manifest-plugin":"^5.0.3","webpack-assets-manifest":"^5.2.1"},"devDependencies":{"babel-loader":"^8.2.4","compression-webpack-plugin":"^9.0.0","esbuild-loader":"^2.18.0","eslint":"^7.32.0","eslint-config-airbnb":"^18.2.1","eslint-config-prettier":"^8.3.0","eslint-plugin-import":"^2.24.2","eslint-plugin-jsx-a11y":"^6.4.1","eslint-plugin-react":"^7.26.0","jest":"^28.1.3","memory-fs":"^0.5.0","swc-loader":"^0.1.15","thenify":"^3.3.1","webpack":"^5.72.0","webpack-merge":"^5.8.0"},"jest":{"testRegex":"(/__tests__/.*|(\\.|/))\\.jsx?$","testPathIgnorePatterns":["/__fixtures__/","/__utils__/"],"roots":["<rootDir>/package"]},"publishConfig":{"access":"public"},"scripts":{"test":"jest","lint":"eslint package/"},"repository":{"type":"git","url":"git+https://github.com/shakacode/shakapacker.git"},"author":{"name":"David Heinemeier Hansson","email":"david@basecamp.com"},"license":"MIT","bugs":{"url":"https://github.com/shakacode/shakapacker/issues"},"homepage":"https://github.com/shakacode/shakapacker","_id":"@agney/shakapacker@6.6.0","gitHead":"a1ce68b4e2671a1ca70fd1727d935b77cc382ddb","_nodeVersion":"22.14.0","_npmVersion":"11.1.0","dist":{"integrity":"sha512-K9gylrj9NybG/06GTel+kIxbF9QbrpAOi8hUyHOqze38XGNgZwvqrHJMMKyNF6z3/ipVURziI3zu2LLg3KxQ5w==","shasum":"176bc9799b994e842e2a6d9464a706d10c137b78","tarball":"https://registry.npmjs.org/@agney/shakapacker/-/shakapacker-6.6.0.tgz","fileCount":49,"unpackedSize":91956,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIDrPPxe9APE4DCX1uWVkmPlz7lXBvCnprAaqct8kV2c5AiEAvc8QSlQmVworfqvXmBV5p52WTDmsp6c9HJ1YIGGJyFg="}]},"_npmUser":{"name":"agney","email":"agney@outlook.in"},"directories":{},"maintainers":[{"name":"agney","email":"agney@outlook.in"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/shakapacker_6.6.0_1740985187578_0.3239115425638759"},"_hasShrinkwrap":false}},"time":{"created":"2025-03-03T06:59:47.506Z","6.6.0":"2025-03-03T06:59:47.770Z","modified":"2025-03-03T06:59:48.747Z"},"maintainers":[{"name":"agney","email":"agney@outlook.in"}],"description":"Use webpack to manage app-like JavaScript modules in Rails","homepage":"https://github.com/shakacode/shakapacker","repository":{"type":"git","url":"git+https://github.com/shakacode/shakapacker.git"},"author":{"name":"David Heinemeier Hansson","email":"david@basecamp.com"},"bugs":{"url":"https://github.com/shakacode/shakapacker/issues"},"license":"MIT","readme":"# Shakapacker\n\n_Official, actively maintained successor to [rails/webpacker](https://github.com/rails/webpacker). Internal naming for `shakapacker` will continue to use `webpacker` where possible for v6. ShakaCode stands behind the long-term maintainence and development of this project for the Rails community._\n\n* See [V6 Upgrade](./docs/v6_upgrade.md) for upgrading from v5 or prior v6 releases.\n\n[![Ruby specs](https://github.com/shakacode/shakapacker/workflows/Ruby%20specs/badge.svg)](https://github.com/shakacode/shakapacker/actions)\n[![Jest specs](https://github.com/shakacode/shakapacker/workflows/Jest%20specs/badge.svg)](https://github.com/shakacode/shakapacker/actions)\n[![Rubocop](https://github.com/shakacode/shakapacker/workflows/Rubocop/badge.svg)](https://github.com/shakacode/shakapacker/actions)\n[![JS lint](https://github.com/shakacode/shakapacker/workflows/JS%20lint/badge.svg)](https://github.com/shakacode/shakapacker/actions)\n\n[![node.js](https://img.shields.io/badge/node-%3E%3D%2012.0.0-brightgreen.svg)](https://www.npmjs.com/package/shakapacker)\n[![Gem](https://img.shields.io/gem/v/shakapacker.svg)](https://rubygems.org/gems/shakapacker)\n[![npm version](https://badge.fury.io/js/shakapacker.svg)](https://badge.fury.io/js/shakapacker)\n\nShakpacker makes it easy to use the JavaScript pre-processor and bundler [Webpack v5+](https://webpack.js.org/)\nto manage frontend JavaScript in Rails. It can coexist with the asset pipeline,\nleaving Webpack responsible solely for frontend JavaScript, or  can be used exclusively, making it also responsible for images, fonts, and CSS.\n\nCheck out 6.1.1+ for [SWC](https://swc.rs/) and [esbuild-loader](https://github.com/privatenumber/esbuild-loader) support! They are faster than Babel!\n\nSee a comparison of [Shakapacker with jsbundling-rails](https://github.com/rails/jsbundling-rails/blob/main/docs/comparison_with_webpacker.md).\n\nFor discussions, see our [Slack Channel](https://reactrails.slack.com/join/shared_invite/enQtNjY3NTczMjczNzYxLTlmYjdiZmY3MTVlMzU2YWE0OWM0MzNiZDI0MzdkZGFiZTFkYTFkOGVjODBmOWEyYWQ3MzA2NGE1YWJjNmVlMGE).\n\n---\n### ShakaCode Support\n\n[ShakaCode](https://www.shakacode.com) offers support for upgrading from webpacker and using Shakapacker. If interested, contact Justin Gordon, [justin@shakacode.com](mailto:justin@shakacode.com). We're also [hiring](https://jobs.lever.co/shakacode/3bdbfdb3-4495-4611-a279-01dddb351abe)!\n\nHere's a testimonial of how ShakaCode can help, from [Florian Gößler](https://github.com/FGoessler) of [Blinkist](https://www.blinkist.com/), January 2, 2023:\n> Hey Justin 👋\n>\n> I just wanted to let you know that we today shipped the webpacker to shakapacker upgrades and it all seems to be running smoothly! Thanks again for all your support and your teams work! 😍\n>\n> On top of your work, it was now also very easy for me to upgrade Tailwind and include our external node_module based web component library which we were using for our other (more modern) apps already. That work is going to be shipped later this week though as we are polishing the last bits of it. 😉\n>\n> Have a great 2023 and maybe we get to work together again later in the year! 🙌\n\n---\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n  - [Prerequisites](#prerequisites)\n  - [Features](#features)\n    - [Optional support](#optional-support)\n  - [Installation](#installation)\n    - [Rails v6+](#rails-v6)\n    - [Note for Yarn v2 usage](#note-for-yarn-v2-usage)\n  - [Concepts](#concepts)\n  - [Usage](#usage)\n    - [Configuration and Code](#configuration-and-code)\n    - [View Helpers](#view-helpers)\n      - [View Helpers `javascript_pack_tag` and `stylesheet_pack_tag`](#view-helpers-javascript_pack_tag-and-stylesheet_pack_tag)\n      - [View Helpers `append_javascript_pack_tag`, `prepend_javascript_pack_tag` and `append_stylesheet_pack_tag`](#view-helper-append_javascript_pack_tag-prepend_javascript_pack_tag-and-append_stylesheet_pack_tag)\n      - [View Helper: `asset_pack_path`](#view-helper-asset_pack_path)\n      - [View Helper: `image_pack_tag`](#view-helper-image_pack_tag)\n      - [View Helper: `favicon_pack_tag`](#view-helper-favicon_pack_tag)\n      - [View Helper: `preload_pack_asset`](#view-helper-preload_pack_asset)\n    - [Images in Stylesheets](#images-in-stylesheets)\n    - [Server-Side Rendering (SSR)](#server-side-rendering-ssr)\n    - [Development](#development)\n      - [Automatic Webpack Code Building](#automatic-webpack-code-building)\n      - [Compiler strategies](#compiler-strategies)\n      - [Common Development Commands](#common-development-commands)\n    - [Webpack Configuration](#webpack-configuration)\n    - [Babel configuration](#babel-configuration)\n    - [SWC configuration](#swc-configuration)\n    - [esbuild loader configuration](#esbuild-loader-configuration)\n    - [Integrations](#integrations)\n      - [React](#react)\n      - [Typescript](#typescript)\n      - [CSS](#css)\n      - [Postcss](#postcss)\n      - [Sass](#sass)\n      - [Less](#less)\n      - [Stylus](#stylus)\n      - [CoffeeScript](#coffeescript)\n      - [Other frameworks](#other-frameworks)\n    - [Custom Rails environments](#custom-rails-environments)\n    - [Upgrading](#upgrading)\n    - [Paths](#paths)\n    - [Additional paths](#additional-paths)\n  - [Deployment](#deployment)\n  - [Example Apps](#example-apps)\n  - [Troubleshooting](#troubleshooting)\n  - [Contributing](#contributing)\n  - [License](#license)\n- [Supporters](#supporters)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Prerequisites\n\n- Ruby 2.6+\n- Rails 5.2+\n- Node.js 12.13.0+ || 14+\n- Yarn\n\n## Features\n- Rails view helpers that fully support Webpack output, including HMR and code splitting.\n- Convenient but not required webpack configuration. The only requirement is that your webpack configuration create a manifest.\n- HMR with the webpack-dev-server, such as for hot-reloading React!\n- Automatic code splitting using multiple entry points to optimize JavaScript downloads.\n- [Webpack v5+](https://webpack.js.org/)\n- ES6 with [babel](https://babeljs.io/), [SWC](https://swc.rs/), or [Esbuild](https://github.com/privatenumber/esbuild-loader)\n- Asset compression, source-maps, and minification\n- CDN support\n- Extensible and configurable. For example, all major dependencies are specified as peers, so you can upgrade easily.\n\n### Optional support\n _Requires extra packages to be installed._\n - React\n - TypeScript\n - Stylesheets - Sass, Less, Stylus and Css, PostCSS\n - CoffeeScript\n\n## Installation\n\n### Rails v6+\n\nWith Rails v6+, skip JavaScript for a new app and follow below Manual Installation Steps to manually add the `shakapacker` gem to your Gemfile.\n```bash\nrails new myapp --skip-javascript\n```\n\n_Note, Rails 6 installs the older v5 version of webpacker unless you specify `--skip-javascript`._\n\nAdd `shakapacker` gem to your `Gemfile`:\n\n```bash\nbundle add shakapacker --strict\n```\n\nThen running the following to install Webpacker:\n\n```bash\n./bin/bundle install\n./bin/rails webpacker:install\n```\n\nWhen `package.json` and/or `yarn.lock` changes, such as when pulling down changes to your local environment in a team settings, be sure to keep your NPM packages up-to-date:\n\n```bash\nyarn\n```\n\nNote, in v6+, most JS packages are peer dependencies. Thus, the installer will add the packages:\n\n```bash\nyarn add @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/runtime babel-loader \\\n  compression-webpack-plugin terser-webpack-plugin \\\n  webpack webpack-assets-manifest webpack-cli webpack-merge webpack-sources webpack-dev-server\n```\n\nPreviously, these \"webpack\" and \"babel\" packages were direct dependencies for `webpacker`. By\nmaking these peer dependencies, you have control over the versions used in your webpack and babel configs.\n\n### Note for Yarn v2 usage\n\nIf you are using Yarn v2 (berry), please note that PnP modules are not supported.\n\nIn order to use Shakapacker with Yarn v2, make sure you set `nodeLinker: node-modules` in your `.yarnrc.yml` file as per the [Yarn docs](https://yarnpkg.com/getting-started/migration#step-by-step) to opt out of Plug'n'Play behaviour.\n\n## Concepts\n\nAt it's core, Shakapacker's essential functionality is to:\n\n1. Provide configuration by a single file used by both Rails view helpers and JavaScript webpack compilation code.\n2. Provide Rails view helpers, utilizing this configuration file, so that a webpage can load JavaScript, CSS, and other static assets compiled by webpack, supporting bundle splitting, fingerprinting, and HMR.\n3. Provide a community supported, default webpack compilation that generates the necessary bundles and manifest, using the same configuration file. This compilation can be extended for any needs.\n\n## Usage\n\n### Configuration and Code\n\nYou will need your file system to correspond to the setup of your `webpacker.yml` file.\n\nSuppose you have the following configuration:\n\n`webpacker.yml`\n```yml\ndefault: &default\n  source_path: app/javascript\n  source_entry_path: packs \n  public_root_path: public\n  public_output_path: packs\n  nested_entries: false\n# And more\n```\n\nAnd that maps to a directory structure like this:\n\n```\napp/javascript:\n  └── packs:               # sets up webpack entries\n  │   └── application.js   # references ../src/my_component.js\n  │   └── application.css\n  └── src:                 # any directory name is fine. Referenced files need to be under source_path\n  │   └── my_component.js\n  └── stylesheets:\n  │   └── my_styles.css\n  └── images:\n      └── logo.svg\npublic/packs                # webpack output\n```\n\nWebpack intelligently includes only necessary files. In this example, the file `packs/application.js` would reference `../src/my_component.js`\n\n`nested_entries` allows you to have webpack entry points nested in subdirectories. This defaults to false so you don't accidentally create entry points for an entire tree of files. In other words, with `nested_entries: false`, you can have your entire `source_path` used for your source (using the `source_entry_path: /`) and you place files at the top level that you want as entry points. `nested_entries: true` allows you to have entries that are in subdirectories. This is useful if you have entries that are generated, so you can have a `generated` subdirectory and easily separate generated files from the rest of your codebase.\n\n### View Helpers\nThe Shakapacker view helpers generate the script and link tags to get the webpack output onto your views.\n\nBe sure to consult the API documentation in the source code of [helper.rb](./lib/webpacker/helper.rb).\n\n**Note:** In order for your styles or static assets files to be available in your view, you would need to link them in your \"pack\" or entry file. Otherwise, Webpack won't know to package up those files.\n\n#### View Helpers `javascript_pack_tag` and `stylesheet_pack_tag`\n\nThese view helpers take your `webpacker.yml` configuration file, along with the resulting webpack compilation `manifest.json` and generates the HTML to load the assets.\n\nYou can then link the JavaScript pack in Rails views using the `javascript_pack_tag` helper. If you have styles imported in your pack file, you can link them by using `stylesheet_pack_tag`:\n\n```erb\n<%= javascript_pack_tag 'application' %>\n<%= stylesheet_pack_tag 'application' %>\n```\n\nThe `javascript_pack_tag` and `stylesheet_pack_tag` helpers will include all the transpiled\npacks with the chunks in your view, which creates html tags for all the chunks.\n\nYou can provide multiple packs and other attributes. Note, `defer` defaults to showing.\n\n```erb\n<%= javascript_pack_tag 'calendar', 'map', 'data-turbolinks-track': 'reload' %>\n```\n\nThe resulting HTML would look like:\n```\n<script src=\"/packs/vendor-16838bab065ae1e314.js\" data-turbolinks-track=\"reload\" defer></script>\n<script src=\"/packs/calendar~runtime-16838bab065ae1e314.js\" data-turbolinks-track=\"reload\" defer></script>\n<script src=\"/packs/calendar-1016838bab065ae1e314.js\" data-turbolinks-track=\"reload\" defer\"></script>\n<script src=\"/packs/map~runtime-16838bab065ae1e314.js\" data-turbolinks-track=\"reload\" defer></script>\n<script src=\"/packs/map-16838bab065ae1e314.js\" data-turbolinks-track=\"reload\" defer></script>\n```\n\nIn this output, both the calendar and map codes might refer to other common libraries. Those get placed something like the vendor bundle. The view helper removes any duplication.\n\nNote, the default of \"defer\" for the `javascript_pack_tag`. You can override that to `false`. If you expose jquery globally with `expose-loader,` by using `import $ from \"expose-loader?exposes=$,jQuery!jquery\"` in your `app/javascript/application.js`, pass the option `defer: false` to your `javascript_pack_tag`.\n\n**Important:** Pass all your pack names as multiple arguments, not multiple calls, when using `javascript_pack_tag` and the `stylesheet_pack_tag`. Otherwise, you will get duplicated chunks on the page. \n\n```erb\n<%# DO %>\n<%= javascript_pack_tag 'calendar', 'map' %>\n\n<%# DON'T %>\n<%= javascript_pack_tag 'calendar' %>\n<%= javascript_pack_tag 'map' %>\n```\nWhile this also generally applies to `stylesheet_pack_tag`, you may use multiple calls to stylesheet_pack_tag if, say, you require multiple <style> tags for different output media:\n\n``` erb\n<%= stylesheet_pack_tag 'application', media: 'screen' %>\n<%= stylesheet_pack_tag 'print', media: 'print' %>\n```\n\n#### View Helper `append_javascript_pack_tag`, `prepend_javascript_pack_tag` and `append_stylesheet_pack_tag`\n\nIf you need configure your script pack names or stylesheet pack names from the view for a route or partials, then you will need some logic to ensure you call the helpers only once with multiple arguments. The new view helpers, `append_javascript_pack_tag` and `append_stylesheet_pack_tag` can solve this problem. The helper `append_javascript_pack_tag` will queue up script packs when the `javascript_pack_tag` is finally used. Similarly,`append_stylesheet_pack_tag` will queue up style packs when the `stylesheet_pack_tag` is finally used.\n\nMain view:\n```erb\n<% append_javascript_pack_tag 'calendar' %>\n<% append_stylesheet_pack_tag 'calendar' %>\n```\n\nSome partial:\n```erb\n<% append_javascript_pack_tag 'map' %>\n<% append_stylesheet_pack_tag 'map' %>\n```\n\nAnd the main layout has:\n```erb\n<%= javascript_pack_tag 'application' %>\n<%= stylesheet_pack_tag 'application' %>\n```\n\nis the same as using this in the main layout:\n\n```erb\n<%= javascript_pack_tag 'calendar', 'map', application' %>\n<%= stylesheet_pack_tag 'calendar', 'map', application' %>\n```\n\nHowever, you typically can't do that in the main layout, as the view and partial codes will depend on the route.\n\nThus, you can distribute the logic of what packs are needed for any route. All the magic of splitting up the code and CSS was automatic!\n\n**Important:** These helpers can be used anywhere in your application as long as they are executed BEFORE `(javascript/stylesheet)_pack_tag` respectively. If you attempt to call one of these helpers after the respective `(javascript/stylesheet)_pack_tag`, an error will be raised.\n\nThe typical issue is that your layout might reference some partials that need to configure packs. A good way to solve this problem is to use `content_for` to ensure that the code to render your partial comes before the call to `javascript_pack_tag`.\n\n```erb\n<% content_for :footer do \n   render 'shared/footer' %>\n   \n<%= javascript_pack_tag %>\n\n<%= content_for :footer %>\n```\n\nThere is also `prepend_javascript_pack_tag` that will put the entry at the front of the queue. This is handy when you want an entry in the main layout to go before the partial and main layout `append_javascript_pack_tag` entries.\n\nMain view:\n```erb\n<% append_javascript_pack_tag 'map' %>\n```\n\nSome partial:\n```erb\n<% append_javascript_pack_tag 'map' %>\n```\n\nAnd the main layout has:\n```erb\n<% prepend_javascript_pack_tag 'main' %>\n<%= javascript_pack_tag 'application' %>\n```\n\nis the same as using this in the main layout:\n\n```erb\n<%= javascript_pack_tag 'main', 'calendar', 'map', application' %>\n```\n\nFor alternative options of setting the additional packs, [see this discussion](https://github.com/shakacode/shakapacker/issues/39).\n\n#### View Helper: `asset_pack_path`\n\nIf you want to link a static asset for `<img />` tag, you can use the `asset_pack_path` helper:\n```erb\n<img src=\"<%= asset_pack_path 'static/logo.svg' %>\" />\n```\n\n#### View Helper: `image_pack_tag`\n\nOr use the dedicated helper:\n```erb\n<%= image_pack_tag 'application.png', size: '16x10', alt: 'Edit Entry' %>\n<%= image_pack_tag 'picture.png', srcset: { 'picture-2x.png' => '2x' } %>\n```\n\n#### View Helper: `favicon_pack_tag`\nIf you want to create a favicon:\n```erb\n<%= favicon_pack_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png' %>\n```\n\n#### View Helper: `preload_pack_asset`\nIf you want to preload a static asset in your `<head>`, you can use the `preload_pack_asset` helper:\n```erb\n<%= preload_pack_asset 'fonts/fa-regular-400.woff2' %>\n```\n\n\n### Images in Stylesheets\nIf you want to use images in your stylesheets:\n\n```css\n.foo {\n  background-image: url('../images/logo.svg')\n}\n```\n\n### Server-Side Rendering (SSR)\n\nNote, if you are using server-side rendering of JavaScript with dynamic code-splitting, as is often done with extensions to Webpacker, like [React on Rails](https://github.com/shakacode/react_on_rails), your JavaScript should create the link prefetch HTML tags that you will use, so you won't need to use to `asset_pack_path` in those circumstances.\n\n### Development\n\nWebpacker ships with two binstubs: `./bin/webpacker` and `./bin/webpacker-dev-server`. Both are thin wrappers around the standard `webpack.js` and `webpack-dev-server.js` executables to ensure that the right configuration files and environmental variables are loaded based on your environment.\n\n_Note: older Shakapacker installations had set a missing NODE_ENV in the binstubs. Please remove this for versions 6.5.2 and newer._\n\n#### Automatic Webpack Code Building\n\nShakapacker can be configured to automatically compile on demand when needed using the `webpacker.yml` `compile` option. This happens when you refer to any of the pack assets using the Shakapacker helper methods. This means that you don't have to run any separate processes. Compilation errors are logged to the standard Rails log. However, this auto-compilation happens when a web request is made that requires an updated webpack build, not when files change. Thus, that can be **painfully slow** for front-end development in this default way. Instead, you should either run the `bin/webpacker --watch` or run `./bin/webpacker-dev-server` during development.\n\nThe `compile: true` option can be more useful for test and production builds.\n\n#### Compiler strategies\n\nShakapacker ships with two different strategies that are used to determine whether assets need recompilation per the `compile: true` option:\n\n- `digest` - This strategy calculates SHA1 digest of files in your watched paths (see below). The calculated digest is then stored in a temp file. To check whether the assets need to be recompiled, Shakapacker calculates the SHA1 of the watched files and compares it with the one stored. If the digests are equal, no recompilation occurs. If the digests are different or the temp file is missing, files are recompiled.\n- `mtime` - This strategy looks at last modified at timestamps of both files AND directories in your watched paths. The timestamp of the most recent file or directory is then compared with the timestamp of `manifest.json` file generated. If the manifest file timestamp is newer than one of the most recently modified file or directory in the watched paths, no recompilation occurs. If the manifest file is order, files are recompiled.\n\nThe `mtime` strategy is generally faster than the `digest` one, but it requires stable timestamps, this makes it perfect for a development environment, such as needing to rebuild bundles for tests, or if you're not changing frontend assets much.\n\nIn production or CI environments, the `digest` strategy is more suitable, unless you are using incremental builds or caching and can guarantee that the timestamps will not change after e.g. cache restore. However, many production or CI environments will explicitly compile assets, so `compile: false` is more appropriate. Otherwise, you'll waste time either checking file timestamps or computing digests.\n\nYou can control what strategy is used by `compiler_strategy` option in `webpacker.yml` config file. By default `mtime` strategy is used in development environment, `digest` is used elsewhere.\n\n**Note:** If you are not using the webpack-dev-server, your packs will be served by Rails public file server. If you've enabled caching (Rails application `config.action_controller.perform_caching` setting), your changes will likely not be picked up due to `Cache-Control` header being set and assets being cached in browser memory. For more details see the [issue #88](https://github.com/shakacode/shakapacker/issues/88).\n\nIf you want to use live code reloading, or you have enough JavaScript that on-demand compilation is too slow, you'll need to run `./bin/webpacker-dev-server`. This process will watch for changes in the relevant files, defined by `webpacker.yml` configuration settings for `source_path`, `source_entry_path`, and `additional_paths`, and it will then automatically reload the browser to match. This feature is also known as [Hot Module Replacement](https://webpack.js.org/concepts/hot-module-replacement/).\n\n#### Common Development Commands\n\n```bash\n# webpack dev server\n./bin/webpacker-dev-server\n\n# watcher\n./bin/webpacker --watch --progress\n\n# standalone build\n./bin/webpacker --progress\n```\n\nOnce you start this webpack development server, Webpacker will automatically start proxying all webpack asset requests to this server. When you stop this server, Rails will detect that it's not running and Rails will revert back to on-demand compilation _if_ you have the `compile` option set to true in your `config/webpacker.yml`\n\nYou can use environment variables as options supported by [webpack-dev-server](https://webpack.js.org/configuration/dev-server/) in the form `WEBPACKER_DEV_SERVER_<OPTION>`. Please note that these environmental variables will always take precedence over the ones already set in the configuration file, and that the _same_ environmental variables must be available to the `rails server` process.\n\n```bash\nWEBPACKER_DEV_SERVER_PORT=4305 WEBPACKER_DEV_SERVER_HOST=example.com WEBPACKER_DEV_SERVER_INLINE=true WEBPACKER_DEV_SERVER_HOT=false ./bin/webpacker-dev-server\n```\n\nBy default, the webpack dev server listens on `localhost:3035` in development for security purposes. However, if you want your app to be available on port 4035 over local LAN IP or a VM instance like vagrant, you can set the `port` and `host` when running `./bin/webpacker-dev-server` binstub:\n\n```bash\nWEBPACKER_DEV_SERVER_PORT=4305 WEBPACKER_DEV_SERVER_HOST=0.0.0.0 ./bin/webpacker-dev-server\n```\n\n**Note:** You need to allow webpack-dev-server host as an allowed origin for `connect-src` if you are running your application in a restrict CSP environment (like Rails 5.2+). This can be done in Rails 5.2+ in the CSP initializer `config/initializers/content_security_policy.rb` with a snippet like this:\n\n```ruby\nRails.application.config.content_security_policy do |policy|\n  policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development?\nend\n```\n\n**Note:** Don't forget to prefix `ruby` when running these binstubs on Windows\n\n\n### Webpack Configuration\n\nFirst, you don't _need_ to use Shakapacker's webpack configuration. However, the `shakapacker` NPM package provides convenient access to configuration code that reads the `config/webpacker.yml` file which the view helpers also use. If you have your own customized webpack configuration, at the minimum, you must ensure:\n\n1. Your output files go the right directory\n2. Your output includes a manifest, via package [`webpack-assets-manifest`](https://github.com/webdeveric/webpack-assets-manifest) that maps output names (your 'packs') to the fingerprinted versions, including bundle-splitting dependencies. That's the main secret sauce of webpacker!\n\nThe most practical webpack configuration is to take the default from Shakapacker and then use [webpack-merge](https://github.com/survivejs/webpack-merge) to merge your customizations with the default. For example, suppose you want to add some `resolve.extensions`:\n\n```js\n// use the new NPM package name, `shakapacker`.\n// merge is webpack-merge from https://github.com/survivejs/webpack-merge\nconst { webpackConfig: baseWebpackConfig, merge } = require('shakapacker')\n\nconst options = {\n  resolve: {\n      extensions: ['.css', '.ts', '.tsx']\n  }\n}\n\n// Copy the object using merge b/c the baseClientWebpackConfig is a mutable global\n// If you want to use this object for client and server rendering configurations,\n// having a new object is essential.\nmodule.exports = merge({}, baseWebpackConfig, options)\n```\n\nThis example is based on [an example project](https://github.com/shakacode/react_on_rails_tutorial_with_ssr_and_hmr_fast_refresh/blob/master/config/webpack/webpack.config.js)\n\nShakapacker gives you a default configuration file `config/webpack/webpack.config.js`, which, by default, you don't need to make any changes to `config/webpack/webpack.config.js` since it's a standard production-ready configuration. However, you will probably want to customize or add a new loader by modifying the webpack configuration, as shown above.\n\nYou might add separate files to keep your code more organized.\n\n```js\n// config/webpack/custom.js\nmodule.exports = {\n  resolve: {\n    alias: {\n      jquery: 'jquery/src/jquery',\n      vue: 'vue/dist/vue.js',\n      React: 'react',\n      ReactDOM: 'react-dom',\n      vue_resource: 'vue-resource/dist/vue-resource'\n    }\n  }\n}\n```\n\nThen `require` this file in your `config/webpack/webpack.config.js`:\n\n```js\n// config/webpack/webpack.config.js\n// use the new NPM package name, `shakapacker`.\nconst { webpackConfig, merge } = require('shakapacker')\nconst customConfig = require('./custom')\n\nmodule.exports = merge(webpackConfig, customConfig)\n```\n\nIf you need access to configs within Shakapacker's configuration, you can import them like so:\n\n```js\n// config/webpack/webpack.config.js\nconst { webpackConfig } = require('shakapacker')\n\nconsole.log(webpackConfig.output_path)\nconsole.log(webpackConfig.source_path)\n\n// Or to print out your whole webpack configuration\nconsole.log(JSON.stringify(webpackConfig, undefined, 2))\n```\n\nYou may want to modify rules in the default configuration. For instance, if you are using a custom svg loader, you may want to remove `.svg` from the default file loader rules. You can search and filter the default rules like so:\n\n```js\nconst svgRule = config.module.rules.find(rule => rule.test.test('.svg'));\nsvgRule.test = svgRule.test.filter(t => !t.test('.svg'))\n```\n\n### Babel configuration\n\nBy default, you will find the Shakapacker preset in your `package.json`. Note, you need to use the new NPM package name, `shakapacker`.\n\n```json\n\"babel\": {\n  \"presets\": [\n    \"./node_modules/shakapacker/package/babel/preset.js\"\n  ]\n},\n```\nOptionally, you can change your Babel configuration by removing these lines in your `package.json` and add [a Babel configuration file](https://babeljs.io/docs/en/config-files) in your project. For an example customization based on the original, see [Customizing Babel Config](./docs/customizing_babel_config.md).\n\n\n### SWC configuration\n\nYou can try out experimental integration with the SWC loader. You can read more at [SWC usage docs](./docs/using_swc_loader.md).\n\nPlease note that if you want opt-in to use SWC, you can skip [React](#react) integration instructions as it is supported out of the box.\n\n### esbuild loader configuration\n\nYou can try out experimental integration with the esbuild-loader. You can read more at [esbuild-loader usage docs](./docs/using_esbuild_loader.md).\n\nPlease note that if you want opt-in to use esbuild-loader, you can skip [React](#react) integration instructions as it is supported out of the box.\n\n### Integrations\n\nShakapacker out of the box supports JS and static assets (fonts, images etc.) compilation. To enable support for CoffeeScript or TypeScript install relevant packages:\n\n#### React\n\nSee here for detailed instructions on how to [configure Shakapacker to bundle a React app](./docs/react.md) (with optional HMR).\n\nSee also [Customizing Babel Config](./docs/customizing_babel_config.md) for an example React configuration.\n\n#### TypeScript\n\n```bash\nyarn add typescript @babel/preset-typescript\n```\n\nBabel won’t perform any type-checking on TypeScript code. To optionally use type-checking run:\n\n```bash\nyarn add fork-ts-checker-webpack-plugin\n```\n\nAdd tsconfig.json\n\n```json\n{\n  \"compilerOptions\": {\n    \"declaration\": false,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"lib\": [\"es6\", \"dom\"],\n    \"module\": \"es6\",\n    \"moduleResolution\": \"node\",\n    \"sourceMap\": true,\n    \"target\": \"es5\",\n    \"jsx\": \"react\",\n    \"noEmit\": true\n  },\n  \"exclude\": [\"**/*.spec.ts\", \"node_modules\", \"vendor\", \"public\"],\n  \"compileOnSave\": false\n}\n```\n\nThen modify the webpack config to use it as a plugin:\n\n```js\n// config/webpack/webpack.config.js\nconst { webpackConfig, merge } = require(\"shakapacker\");\nconst ForkTSCheckerWebpackPlugin = require(\"fork-ts-checker-webpack-plugin\");\n\nmodule.exports = merge(webpackConfig, {\n  plugins: [new ForkTSCheckerWebpackPlugin()],\n});\n```\n\n#### CSS\n\nTo enable CSS support in your application, add following packages:\n\n```bash\nyarn add css-loader style-loader mini-css-extract-plugin css-minimizer-webpack-plugin\n```\n\nOptionally, add the `CSS` extension to webpack config for easy resolution.\n\n```js\n// config/webpack/webpack.config.js\nconst { webpackConfig, merge } = require('shakapacker')\nconst customConfig = {\n  resolve: {\n    extensions: ['.css']\n  }\n}\n\nmodule.exports = merge(webpackConfig, customConfig)\n```\n\nTo enable `PostCSS`, `Sass` or `Less` support, add `CSS` support first and\nthen add the relevant pre-processors:\n\n#### Postcss\n\n```bash\nyarn add postcss postcss-loader\n```\n\nOptionally add these two plugins if they are required in your `postcss.config.js`:\n```bash\nyarn add postcss-preset-env postcss-flexbugs-fixes\n```\n\n#### Sass\n\n```bash\nyarn add sass sass-loader\n```\n\n#### Less\n\n```bash\nyarn add less less-loader\n```\n\n#### Stylus\n\n```bash\nyarn add stylus stylus-loader\n```\n\n#### CoffeeScript\n\n```bash\nyarn add coffeescript coffee-loader\n```\n\n#### Other frameworks\n\nPlease follow webpack integration guide for relevant framework or library,\n\n1. [Svelte](https://github.com/sveltejs/svelte-loader#install)\n2. [Angular](https://v2.angular.io/docs/ts/latest/guide/webpack.html#!#configure-webpack)\n3. [Vue](https://vue-loader.vuejs.org/guide/)\n\nFor example to add Vue support:\n```js\n// config/webpack/rules/vue.js\nconst { VueLoaderPlugin } = require('vue-loader')\n\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.vue$/,\n        loader: 'vue-loader'\n      }\n    ]\n  },\n  plugins: [new VueLoaderPlugin()],\n  resolve: {\n    extensions: ['.vue']\n  }\n}\n```\n\n```js\n// config/webpack/webpack.config.js\nconst { webpackConfig, merge } = require('shakapacker')\nconst vueConfig = require('./rules/vue')\n\nmodule.exports = merge(vueConfig, webpackConfig)\n```\n\n### Custom Rails environments\n\nOut of the box Shakapacker ships with - development, test and production environments in `config/webpacker.yml` however, in most production apps extra environments are needed as part of deployment workflow. Shakapacker supports this out of the box from version 3.4.0+ onwards.\n\nYou can choose to define additional environment configurations in webpacker.yml,\n\n```yml\nstaging:\n  <<: *default\n\n  # Production depends on precompilation of packs prior to booting for performance.\n  compile: false\n\n  # Cache manifest.json for performance\n  cache_manifest: true\n\n  # Compile staging packs to a separate directory\n  public_output_path: packs-staging\n```\n\nOtherwise Shakapacker will use production environment as a fallback environment for loading configurations. Please note, `NODE_ENV` can either be set to `production`, `development` or `test`. This means you don't need to create additional environment files inside `config/webpacker/*` and instead use webpacker.yml to load different configurations using `RAILS_ENV`.\n\nFor example, the below command will compile assets in production mode but will use staging configurations from `config/webpacker.yml` if available or use fallback production environment configuration:\n\n```bash\nRAILS_ENV=staging bundle exec rails assets:precompile\n```\n\nAnd, this will compile in development mode and load configuration for cucumber environment if defined in webpacker.yml or fallback to production configuration\n\n```bash\nRAILS_ENV=cucumber NODE_ENV=development bundle exec rails assets:precompile\n```\n\nPlease note, binstubs compiles in development mode however rake tasks compiles in production mode.\n\n```bash\n# Compiles in development mode unless NODE_ENV is specified, per the binstub source\n./bin/webpacker\n./bin/webpacker-dev-server\n\n# Compiles in production mode by default unless NODE_ENV is specified, per `lib/tasks/webpacker/compile.rake`\nbundle exec rails assets:precompile\nbundle exec rails webpacker:compile\n```\n\n### Upgrading\n\nYou can run following commands to upgrade Shakapacker to the latest stable version. This process involves upgrading the gem and related JavaScript packages:\n\n```bash\n# check your Gemfile for version restrictions\nbundle update shakapacker\n\n# overwrite your changes to the default install files and revert any unwanted changes from the install\nrails webpacker:install\n\n# yarn 1 instructions\nyarn upgrade shakapacker --latest\nyarn upgrade webpack-dev-server --latest\n\n# yarn 2 instructions\nyarn up shakapacker@latest\nyarn up webpack-dev-server@latest\n\n# Or to install the latest release (including pre-releases)\nyarn add shakapacker@next\n```\n\nAlso, consult the [CHANGELOG](./CHANGELOG.md) for additional upgrade links.\n\n### Paths\n\nBy default, Shakapacker ships with simple conventions for where the JavaScript app files and compiled webpack bundles will go in your Rails app. All these options are configurable from `config/webpacker.yml` file.\n\nThe configuration for what webpack is supposed to compile by default rests on the convention that every file in `app/javascript/`**(default)** or whatever path you set for `source_entry_path` in the `webpacker.yml` configuration is turned into their own output files (or entry points, as webpack calls it). Therefore you don't want to put any file inside `app/javascript` directory that you do not want to be an entry file. As a rule of thumb, put all files you want to link in your views inside \"app/javascript/\" directory and keep everything else under subdirectories like `app/javascript/controllers`.\n\nSuppose you want to change the source directory from `app/javascript` to `frontend` and output to `assets/packs`. This is how you would do it:\n\n```yml\n# config/webpacker.yml\nsource_path: frontend # packs are the files in frontend/\npublic_output_path: assets/packs # outputs to => public/assets/packs\n```\n\nSimilarly you can also control and configure `webpack-dev-server` settings from `config/webpacker.yml` file:\n\n```yml\n# config/webpacker.yml\ndevelopment:\n  dev_server:\n    host: localhost\n    port: 3035\n```\n\nIf you have `hmr` turned to true and `inline_css` is not false, then the `stylesheet_pack_tag` generates no output, as you will want to configure your styles to be inlined in your JavaScript for hot reloading. During production and testing, the `stylesheet_pack_tag` will create the appropriate HTML tags.\n\nIf you want to have HMR and separate link tags, set `hmr: true` and `inline_css: false`. This will cause styles to be extracted and reloaded with the `mini-css-extract-plugin` loader. Note that in this scenario, you do not need to include style-loader in your project dependencies.\n\n### Additional paths\n\nIf you are adding Shakapacker to an existing app that has most of the assets inside `app/assets` or inside an engine, and you want to share that with webpack modules, you can use the `additional_paths` option available in `config/webpacker.yml`. This lets you\nadd additional paths that webpack should look up when resolving modules:\n\n```yml\nadditional_paths: ['app/assets', 'vendor/assets']\n```\n\nYou can then import these items inside your modules like so:\n\n```js\n// Note it's relative to parent directory i.e. app/assets\nimport 'stylesheets/main'\nimport 'images/rails.png'\n```\n\n**Note:** Please be careful when adding paths here otherwise it will make the compilation slow, consider adding specific paths instead of whole parent directory if you just need to reference one or two modules\n\n**Also note:** While importing assets living outside your `source_path` defined in webpacker.yml (like, for instance, assets under `app/assets`) from within your packs using _relative_ paths like `import '../../assets/javascripts/file.js'` will work in development, Shakapacker won't recompile the bundle in production unless a file that lives in one of it's watched paths has changed (check out `Webpacker::MtimeStrategy#latest_modified_timestamp` or `Webpacker::DigestStrategy#watched_files_digest` depending on strategy configured by `compiler_strategy` option in `webpacker.yml`). That's why you'd need to add `app/assets` to the additional_paths as stated above and use `import 'javascripts/file.js'` instead.\n\n\n## Deployment\n\nShakapacker hooks up a new `webpacker:compile` task to `assets:precompile`, which gets run whenever you run `assets:precompile`. If you are not using Sprockets, `webpacker:compile` is automatically aliased to `assets:precompile`. Similar to sprockets both rake tasks will compile packs in production mode but will use `RAILS_ENV` to load configuration from `config/webpacker.yml` (if available).\n\nThis behavior is optional & can be disabled by either setting an `WEBPACKER_PRECOMPILE` environment variable to `false`, `no`, `n`, or `f`, or by setting a `webpacker_precompile` key in your `webpacker.yml` to `false`. ([source code](./lib/webpacker/configuration.rb#L30))\n\nWhen compiling assets for production on a remote server, such as a continuous integration environment, it's recommended to use `yarn install --frozen-lockfile` to install NPM packages on the remote host to ensure that the installed packages match the `yarn.lock` file.\n\nIf you are using a CDN setup, webpacker will use the configured [asset host](https://guides.rubyonrails.org/configuring.html#rails-general-configuration) value to prefix URLs for images or font icons which are included inside JS code or CSS. It is possible to override this value during asset compilation by setting the `WEBPACKER_ASSET_HOST` environment variable.\n\n## Example Apps\n* [React on Rails Tutorial With SSR, HMR fast refresh, and TypeScript](https://github.com/shakacode/react_on_rails_tutorial_with_ssr_and_hmr_fast_refresh)\n\n\n## Troubleshooting\n\nSee the doc page for [Troubleshooting](./docs/troubleshooting.md).\n\n## Contributing\n\nWe encourage you to contribute to Shakapacker/Webpacker! See [CONTRIBUTING](CONTRIBUTING.md) for guidelines about how to proceed. We have a [Slack discussion channel](https://reactrails.slack.com/join/shared_invite/enQtNjY3NTczMjczNzYxLTlmYjdiZmY3MTVlMzU2YWE0OWM0MzNiZDI0MzdkZGFiZTFkYTFkOGVjODBmOWEyYWQ3MzA2NGE1YWJjNmVlMGE).\n\n## License\n\nWebpacker is released under the [MIT License](https://opensource.org/licenses/MIT).\n  \n## Supporters\n\n<a href=\"https://www.jetbrains.com\">\n  <img src=\"https://user-images.githubusercontent.com/4244251/184881139-42e4076b-024b-4b30-8c60-c3cd0e758c0a.png\" alt=\"JetBrains\" height=\"120px\">\n</a>\n<a href=\"https://scoutapp.com\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://user-images.githubusercontent.com/4244251/184881147-0d077438-3978-40da-ace9-4f650d2efe2e.png\">\n    <source media=\"(prefers-color-scheme: light)\" srcset=\"https://user-images.githubusercontent.com/4244251/184881152-9f2d8fba-88ac-4ba6-873b-22387f8711c5.png\">\n    <img alt=\"ScoutAPM\" src=\"https://user-images.githubusercontent.com/4244251/184881152-9f2d8fba-88ac-4ba6-873b-22387f8711c5.png\" height=\"120px\">\n  </picture>\n</a>\n<br />\n<a href=\"https://www.browserstack.com\">\n  <picture>\n    <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://user-images.githubusercontent.com/4244251/184881122-407dcc29-df78-4b20-a9ad-f597b56f6cdb.png\">\n    <source media=\"(prefers-color-scheme: light)\" srcset=\"https://user-images.githubusercontent.com/4244251/184881129-e1edf4b7-3ae1-4ea8-9e6d-3595cf01609e.png\">\n    <img alt=\"BrowserStack\" src=\"https://user-images.githubusercontent.com/4244251/184881129-e1edf4b7-3ae1-4ea8-9e6d-3595cf01609e.png\" height=\"55px\">\n  </picture>\n</a>\n<a href=\"https://railsautoscale.com\">\n  <img src=\"https://user-images.githubusercontent.com/4244251/184881144-95c2c25c-9879-4069-864d-4e67d6ed39d2.png\" alt=\"Rails Autoscale\" height=\"55px\">\n</a>\n<a href=\"https://www.honeybadger.io\">\n  <img src=\"https://user-images.githubusercontent.com/4244251/184881133-79ee9c3c-8165-4852-958e-31687b9536f4.png\" alt=\"Honeybadger\" height=\"55px\">\n</a>\n\n<br />\n<br />\n\nThe following companies support our open source projects, and ShakaCode uses their products!\n","readmeFilename":"README.md"}