webpacker-5.4.3/0000755000004100000410000000000014123265223013516 5ustar www-datawww-datawebpacker-5.4.3/Gemfile.lock0000644000004100000410000001066314123265223015746 0ustar www-datawww-dataPATH remote: . specs: webpacker (5.4.0) activesupport (>= 5.2) rack-proxy (>= 0.6.1) railties (>= 5.2) semantic_range (>= 2.3.0) GEM remote: https://rubygems.org/ specs: actioncable (6.1.3.2) actionpack (= 6.1.3.2) activesupport (= 6.1.3.2) nio4r (~> 2.0) websocket-driver (>= 0.6.1) actionmailbox (6.1.3.2) actionpack (= 6.1.3.2) activejob (= 6.1.3.2) activerecord (= 6.1.3.2) activestorage (= 6.1.3.2) activesupport (= 6.1.3.2) mail (>= 2.7.1) actionmailer (6.1.3.2) actionpack (= 6.1.3.2) actionview (= 6.1.3.2) activejob (= 6.1.3.2) activesupport (= 6.1.3.2) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 2.0) actionpack (6.1.3.2) actionview (= 6.1.3.2) activesupport (= 6.1.3.2) rack (~> 2.0, >= 2.0.9) rack-test (>= 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.2.0) actiontext (6.1.3.2) actionpack (= 6.1.3.2) activerecord (= 6.1.3.2) activestorage (= 6.1.3.2) activesupport (= 6.1.3.2) nokogiri (>= 1.8.5) actionview (6.1.3.2) activesupport (= 6.1.3.2) builder (~> 3.1) erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.1, >= 1.2.0) activejob (6.1.3.2) activesupport (= 6.1.3.2) globalid (>= 0.3.6) activemodel (6.1.3.2) activesupport (= 6.1.3.2) activerecord (6.1.3.2) activemodel (= 6.1.3.2) activesupport (= 6.1.3.2) activestorage (6.1.3.2) actionpack (= 6.1.3.2) activejob (= 6.1.3.2) activerecord (= 6.1.3.2) activesupport (= 6.1.3.2) marcel (~> 1.0.0) mini_mime (~> 1.0.2) activesupport (6.1.3.2) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) zeitwerk (~> 2.3) ast (2.4.2) builder (3.2.4) byebug (11.1.3) concurrent-ruby (1.1.8) crass (1.0.6) erubi (1.10.0) globalid (0.4.2) activesupport (>= 4.2.0) i18n (1.8.10) concurrent-ruby (~> 1.0) loofah (2.9.1) crass (~> 1.0.2) nokogiri (>= 1.5.9) mail (2.7.1) mini_mime (>= 0.1.1) marcel (1.0.1) method_source (1.0.0) mini_mime (1.0.3) mini_portile2 (2.5.1) minitest (5.14.4) nio4r (2.5.7) nokogiri (1.11.4) mini_portile2 (~> 2.5.0) racc (~> 1.4) parallel (1.20.1) parser (3.0.1.1) ast (~> 2.4.1) racc (1.5.2) rack (2.2.3) rack-proxy (0.6.5) rack rack-test (1.1.0) rack (>= 1.0, < 3) rails (6.1.3.2) actioncable (= 6.1.3.2) actionmailbox (= 6.1.3.2) actionmailer (= 6.1.3.2) actionpack (= 6.1.3.2) actiontext (= 6.1.3.2) actionview (= 6.1.3.2) activejob (= 6.1.3.2) activemodel (= 6.1.3.2) activerecord (= 6.1.3.2) activestorage (= 6.1.3.2) activesupport (= 6.1.3.2) bundler (>= 1.15.0) railties (= 6.1.3.2) sprockets-rails (>= 2.0.0) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) rails-html-sanitizer (1.3.0) loofah (~> 2.3) railties (6.1.3.2) actionpack (= 6.1.3.2) activesupport (= 6.1.3.2) method_source rake (>= 0.8.7) thor (~> 1.0) rainbow (3.0.0) rake (13.0.3) regexp_parser (2.1.1) rexml (3.2.5) rubocop (0.93.1) parallel (~> 1.10) parser (>= 2.7.1.5) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8) rexml rubocop-ast (>= 0.6.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 2.0) rubocop-ast (1.5.0) parser (>= 3.0.1.1) rubocop-performance (1.10.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) semantic_range (3.0.0) sprockets (4.0.2) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.2.2) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) thor (1.1.0) tzinfo (2.0.4) concurrent-ruby (~> 1.0) unicode-display_width (1.7.0) websocket-driver (0.7.3) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) zeitwerk (2.4.2) PLATFORMS ruby DEPENDENCIES bundler (>= 1.3.0) byebug minitest (~> 5.0) rack-proxy rails rake (>= 11.1) rubocop (= 0.93.1) rubocop-performance semantic_range webpacker! BUNDLED WITH 2.2.3 webpacker-5.4.3/docs/0000755000004100000410000000000014123265223014446 5ustar www-datawww-datawebpacker-5.4.3/docs/target.md0000644000004100000410000000153314123265223016260 0ustar www-datawww-data# Target browsers By default webpacker provides these front-end tools: - [@babel/preset-env](https://github.com/babel/babel/tree/master/packages/babel-preset-env) - [Autoprefixer](https://github.com/postcss/autoprefixer) - [postcss-preset-env](https://github.com/csstools/postcss-preset-env) All these tools use [Browserslist](https://github.com/browserslist/browserslist) to detect which environment your users have Webpacker browserslist default target: ``` defaults ``` `defaults`: `(> 0.5%, last 2 versions, Firefox ESR, not dead)`, [browserl.ist](https://browserl.ist/) is an online tool to check what browsers will be selected by some query. To keep browsers data up to date, you need to run: ```bash yarn upgrade caniuse-lite ``` at least once every few months, to prevent such [problems](https://github.com/browserslist/browserslist/issues/492) webpacker-5.4.3/docs/deployment.md0000644000004100000410000001161614123265223017155 0ustar www-datawww-data# Deployment Webpacker 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`. Remember to set NODE_ENV environment variable to production during deployment or when running the rake task. The `javascript_pack_tag` and `stylesheet_pack_tag` helper method will automatically insert the correct HTML tag for compiled pack. Just like the asset pipeline does it. By default the output will look like this in different environments: ```html ``` ## Heroku In order for your Webpacker app to run on Heroku, you'll need to do a bit of configuration before hand. ``` heroku create my-webpacker-heroku-app heroku addons:create heroku-postgresql:hobby-dev heroku buildpacks:add heroku/nodejs heroku buildpacks:add heroku/ruby git push heroku master ``` We're essentially doing the following here: * Creating an app on Heroku * Creating a Postgres database for the app (this is assuming that you're using Heroku Postgres for your app) * Adding the Heroku NodeJS and Ruby buildpacks for your app. This allows the `npm` or `yarn` executables to properly function when compiling your app - as well as Ruby. * Pushing our code to Heroku and kicking off the deployment ## Nginx Webpacker doesn't serve anything in production. You’re expected to configure your web server to serve files in public/ directly. Some servers support sending precompressed versions of files when they're available. For example, nginx offers a `gzip_static` directive that serves files with the `.gz` extension to supported clients. With an optional module, nginx can also serve Brotli compressed files with the `.br` extension (see below for installation and configuration instructions). Here's a sample nginx site config for a Rails app using Webpacker: ```nginx upstream app { # server unix:///path/to/app/tmp/puma.sock; } server { listen 80; server_name www.example.com; root /path/to/app/public; location @app { proxy_pass http://app; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location / { try_files $uri @app; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } location ~ /\.(?!well-known).* { deny all; } location ~ ^/(assets|packs)/ { gzip_static on; brotli_static on; # Optional, see below expires max; add_header Cache-Control public; } } ``` ### Installing the ngx_brotli module If you want to serve Brotli compressed files with nginx, you will need to install the `nginx_brotli` module. Installation instructions from source can be found in the official [google/ngx_brotli](https://github.com/google/ngx_brotli) git repository. Alternatively, depending on your platform, the module might be available via a pre-compiled package. Once installed, you need to load the module. As we want to serve the pre-compressed files, we only need the static module. Add the following line to your `nginx.conf` file and reload nginx: ``` load_module modules/ngx_http_brotli_static_module.so; ``` Now, you can set `brotli_static on;` in your nginx site config, as per the config in the last section above. ## CDN Webpacker out-of-the-box provides CDN support using your Rails app `config.action_controller.asset_host` setting. If you already have [CDN](http://guides.rubyonrails.org/asset_pipeline.html#cdns) added in your Rails app you don't need to do anything extra for Webpacker, it just works. ## Capistrano ### Assets compiling on every deployment even if JavaScript and CSS files are not changed Make sure you have `public/packs` and `node_modules` in `:linked_dirs` ```ruby append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/packs", ".bundle", "node_modules" ``` If you have `node_modules` added to `:linked_dirs` you'll need to run yarn install before `deploy:assets:precompile`, so you can add this code snippet at the bottom deploy.rb ```ruby before "deploy:assets:precompile", "deploy:yarn_install" namespace :deploy do desc "Run rake yarn install" task :yarn_install do on roles(:web) do within release_path do execute("cd #{release_path} && yarn install --silent --no-progress --no-audit --no-optional") end end end end ``` webpacker-5.4.3/docs/assets.md0000644000004100000410000000613614123265223016300 0ustar www-datawww-data# Assets Static assets like images and fonts support is enabled out-of-box and you can link them into your JavaScript app code and have them compiled automatically. ## Import from node modules You can also import styles from `node_modules` using the following syntax. Please note that your styles will always be extracted into `[pack_name].css`: ```sass // app/javascript/styles.sass // ~ to tell webpack that this is not a relative import: @import '~@material/animation/mdc-animation' @import '~bootstrap/dist/css/bootstrap' ``` ```js // Your main app pack // app/javascript/packs/app.js import '../styles' ``` ```erb <%# In your views %> <%= javascript_pack_tag 'app' %> <%= stylesheet_pack_tag 'app' %> ``` ## Import from Sprockets using helpers It's possible to link to assets that have been precompiled by Sprockets. Add the `.erb` extension to your JavaScript file, then you can use Sprockets' asset helpers: ```erb <%# app/javascript/my_pack/example.js.erb %> <% helpers = ActionController::Base.helpers %> const railsImagePath = "<%= helpers.image_path('rails.png') %>" ``` This is enabled by the `rails-erb-loader` loader rule in `config/webpack/loaders/erb.js`. ## Using babel module resolver You can also use [babel-plugin-module-resolver](https://github.com/tleunen/babel-plugin-module-resolver) to reference assets directly from `app/assets/**` ```bash yarn add babel-plugin-module-resolver ``` Specify the plugin in your `babel.config.js` with the custom root or alias. Here's an example: ```js { plugins: [ [require("babel-plugin-module-resolver").default, { "root": ["./app"], "alias": { "assets": "./assets" } }] ] } ``` And then within your javascript app code: ```js // Note: we don't have to do any ../../ jazz import FooImage from 'assets/images/foo-image.png' import 'assets/stylesheets/bar' ``` ## Link in your Rails views You can also link `js/images/styles/fonts` used within your js app in views using `asset_pack_path` and `image_pack_tag` helpers. These helpers are useful in cases where you just want to create a `` or `` for an asset. ```yml app/javascript: - packs - app.js - images - calendar.png ``` ```js // app/javascript/packs/app.js (or any of your packs) // import all image files in a folder: require.context('../images', true) ``` ```erb <%# Rails view, for example app/views/layouts/application.html.erb %> <% # => %> <%= image_pack_tag 'media/images/calendar.png' %> <% # => %> <%# no path resolves to default 'images' folder: %> <%= image_pack_tag 'calendar.png' %> <% # => %> ``` Note you need to add a `media/` prefix (not `/media/`) to any subfolder structure you might have in `app/javascript`. See more examples in the [tests](https://github.com/rails/webpacker/blob/0b86cadb5ed921e2c1538382e72a236ec30a5d97/test/helper_test.rb#L37). webpacker-5.4.3/docs/typescript.md0000644000004100000410000001206014123265223017175 0ustar www-datawww-data# TypeScript ## Installation 1. Run the TypeScript installer ```bash bundle exec rails webpacker:install:typescript ``` After that, a new file called `hello_typescript.ts` will be present in your `packs` directory (or rather the `source_entry_path` of your `webpacker.yml` configuration). You're now ready to write TypeScript. ## (Optional) Adding Compile-Time Type Checking The default installation only transpiles your TypeScript code using Babel. If you would like to enable type checking as part of the Webpack compilation process (i.e. fail the build if there are TS errors), you can do the following: 1. Install the Fork TS Checker Webpack Plugin ```sh yarn add --dev fork-ts-checker-webpack-plugin ``` 2. Then add it to your development environment config in `config/webpack/development.js` ```js const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin"); const path = require("path"); environment.plugins.append( "ForkTsCheckerWebpackPlugin", new ForkTsCheckerWebpackPlugin({ typescript: { configFile: path.resolve(__dirname, "../../tsconfig.json"), }, async: false, }) ); ``` If you are `fork-ts-checker-webpack-plugin` older than 5.0, the `tsconfig` option also needs to be specified: ```js const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin"); const path = require("path"); environment.plugins.append( "ForkTsCheckerWebpackPlugin", new ForkTsCheckerWebpackPlugin({ // this is a relative path to your project's TypeScript config tsconfig: path.resolve(__dirname, "../../tsconfig.json"), // non-async so type checking will block compilation async: false, }) ); ``` ## Upgrading to 5.1 If you update your App to `webpacker >= 5.1` and had TypeScript installed before, you need to add some new/remove some old configurations: 1. Remove old packages: - `yarn remove ts-loader` 2. Add new packages: - `yarn add @babel/preset-typescript` 3. Remove old configuration files: - Delete this file: `config/webpack/loaders/typescript.js` 4. Remove the following lines from `config/webpack/environment.js`: - `const typescript = require('./loaders/typescript')` - `environment.loaders.prepend('typescript', typescript)` 5. Add the TypeScript preset to your `babel.config.js`: - This line `['@babel/preset-typescript', { 'allExtensions': true, 'isTSX': true }]` has to be added as the last item to the `presets` array in your `babel.config.js` ### Upgrading to 5.1 for Vue users 1. Remove old packages: - `yarn remove ts-loader pnp-webpack-plugin` 2. Follow point 3 and 4 from the `TypeScript with Vue components` section ## TypeScript with React 1. Setup react using Webpacker [react installer](../README.md#react). Then run the TypeScript installer ```bash bundle exec rails webpacker:install:typescript ``` 2. Rename the generated `hello_react.js` to `hello_react.tsx`. Make the file valid TypeScript and now you can use TypeScript, JSX with React. ## TypeScript with Vue components 1. Setup Vue using the Webpacker [Vue installer](../README.md#vue). Then run the TypeScript installer ```bash bundle exec rails webpacker:install:typescript ``` 2. Rename generated `hello_vue.js` to `hello_vue.ts`. 3. Install the right Babel preset: `yarn add babel-preset-typescript-vue` 4. Change the generated `babel.config.js` from ```js ["@babel/preset-typescript", { "allExtensions": true, "isTSX": true }] ``` to ```js ["babel-preset-typescript-vue", { "allExtensions": true, "isTSX": true }] ``` and now you can use ` ``` ```js document.addEventListener('DOMContentLoaded', () => { // Get the properties BEFORE the app is instantiated const node = document.getElementById('hello-vue') const props = JSON.parse(node.getAttribute('data')) // Render component with props new Vue({ render: h => h(App, { props }) }).$mount('#hello-vue'); }) ``` You can follow same steps for Angular too. ## Elm Just like with other implementations, we'll render our data inside a `data` attribute: ```erb <%= content_tag :div, id: "hello-elm", data: { message: "Hello", name: "David" }.to_json do %> <% end %> ``` We parse the JSON data and pass it to Elm as flags: ```js import Elm from '../Main' document.addEventListener('DOMContentLoaded', () => { const node = document.getElementById('hello-elm') const data = JSON.parse(node.getAttribute('data')) Elm.Main.embed(node, data) }) ``` Defining `Flags` as a `type alias`, we instruct Elm to demand flags `message` and `name` of type `String` on initialization. Using `programWithFlags` we bring all the pieces together: ```elm module Main exposing (..) import Html exposing (Html, programWithFlags, h1, text) import Html.Attributes exposing (style) -- MODEL type alias Flags = { message : String , name : String } type alias Model = { message : String , name : String } type Msg = NoOp -- INIT init : Flags -> ( Model, Cmd Msg ) init flags = let { message, name } = flags in ( Model message name, Cmd.none ) -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of NoOp -> ( model, Cmd.none ) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- VIEW view : Model -> Html Msg view model = h1 [ style [ ( "display", "flex" ), ( "justify-content", "center" ) ] ] [ text (model.message ++ ", " ++ model.name ++ "!") ] -- MAIN main : Program Flags Model Msg main = programWithFlags { view = view , init = init , update = update , subscriptions = subscriptions } ``` webpacker-5.4.3/docs/css.md0000644000004100000410000002132314123265223015561 0ustar www-datawww-data# CSS, Sass and SCSS Webpacker supports importing CSS, Sass and SCSS files directly into your JavaScript files. Importing and loading styles is a two step process: 1. You need to tell webpack which file(s) it has to compile and know how to load When you do `import '../scss/application.scss'`, you're telling webpack to include `application.scss` in the build. This does not mean it's going to be compiled into your javascript, only that webpack now compiles and knows how to load this file. (How that file compilation is handled is depending on how your loaders (`css-loader`, `sass-loader`, `file-loader`, etc.) are configured.) 2. You need to load those files in your views In order to have styles load in production, you need to include `stylesheet_pack_tag` with the same name as the javascript file that imports the styles. When you do `<%= stylesheet_pack_tag 'application' %>`, that's a run-time inclusion from Rails, where Rails gets the correct "asset path" to that file from webpack. ## Import global styles into your JS app ### Importing CSS as a multi-file pack (Webpacker v5) When you add a CSS/SCSS/SASS file to `app/javascript/packs/` directory, make sure to use the same pack name as its complementary JavaScript pack, e.g. `application.js` and `application.css`. By Webpacker convention (as of Webpacker v5), this will bundle `application.js` and `application.scss` as part of the same entry point (also described as [a multi-file entry point in the webpack docs](https://webpack.js.org/concepts/entry-points/#single-entry-shorthand-syntax)). With this approach, you can avoid importing CSS from JS, if desired. ``` app/ javascript/ packs/ application.js application.scss ``` ### Importing CSS from CSS You can import additional CSS/SCSS/SASS files from within a CSS file: ``` app/ javascript/ stylesheets/ application.scss posts.scss comments.scss ``` ```css /* app/javascript/stylesheets/application.scss */ @import './posts'; @import './comments'; ``` ### Importing CSS provided by an NPM package from SCSS/CSS Given your application installs an NPM package that provides CSS, such as `flatpickr`, you can import the CSS file(s) by path from the package directory within `node_modules/`: ```js /* app/javascript/stylesheets/application.scss */ @import "flatpickr/dist/flatpickr.css" ``` ### Importing CSS from JS ```sass // app/javascript/hello_react/styles/hello-react.sass .hello-react padding: 20px font-size: 12px ``` ```js // React component example // app/javascript/packs/hello_react.jsx import React from 'react' import helloIcon from '../hello_react/images/icon.png' import '../hello_react/styles/hello-react' const Hello = props => (
hello-icon

Hello {props.name}!

) ``` ### Importing CSS provided by an NPM package from JS Given your application installs an NPM package that provides CSS, such as `flatpickr`, you can import the CSS file(s) by path from the package directory within `node_modules/`. This is an alternative to importing from within a CSS file, as above: ```js // app/javascript/packs/application.js import "flatpickr/dist/flatpickr.css" ``` ## Import scoped styles into your JS app Stylesheets that end with `.module.*` are treated as [CSS Modules](https://github.com/css-modules/css-modules). ```sass // app/javascript/hello_react/styles/hello-react.module.sass .helloReact padding: 20px font-size: 12px ``` ```js // React component example // app/javascript/packs/hello_react.jsx import React from 'react' import helloIcon from '../hello_react/images/icon.png' import styles from '../hello_react/styles/hello-react' const Hello = props => (
hello-icon

Hello {props.name}!

) ``` **Note:** Declared class is referenced as object property in JavaScript. ## Import scoped styles into your TypeScript app Using CSS modules with a TypeScript application requires a few differences from a JavaScript app. The CSS / Sass files are the same: ```sass // app/javascript/hello_react/styles/hello-react.module.sass .helloReact padding: 20px font-size: 12px ``` There must also be a type definition file for these styles: ```typescript export const helloReact: string; ``` You can then import the styles like this: ```typescript // React component example // app/javascripts/packs/hello_react.tsx import React from 'react' import helloIcon from '../hello_react/images/icon.png' import * as styles from '../hello_react/styles/hello-react.module.sass' const Hello = props => (
hello-icon

Hello {props.name}!

) ``` You can automatically generate type definitions for the styles by installing the `typed-scss-modules` as a development dependency: ``` yarn add typed-scss-modules --dev ``` Then by adding these lines to your `package.json`: ``` "scripts": { "gen-typings": "yarn run tsm app/javascript/**/*.sass", "watch-typings": "yarn run tsm app/javascript/**/*.sass -w" }, ``` You can generate the typings for the stylesheet by running the command `yarn gen-typings` when you've finished writing CSS, or run `yarn watch-typings` to have it automatically generate them as you go. ## Link styles from your Rails views Under the hood webpack uses [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) plugin to extract all the referenced styles within your app and compile it into a separate `[pack_name].css` bundle so that in your view you can use the `stylesheet_pack_tag` helper. ```erb <%= stylesheet_pack_tag 'hello_react' %> ``` Webpacker emits css files only if `extract_css` is set to true in webpacker.yml otherwise `stylesheet_pack_tag` returns nil. ## Add bootstrap You can use Yarn to add bootstrap or any other modules available on npm: ```bash yarn add bootstrap ``` Import Bootstrap and theme (optional) CSS in your app/javascript/packs/application.js file: ```js import 'bootstrap/dist/css/bootstrap' import 'bootstrap/dist/css/bootstrap-theme' ``` Or in your app/javascript/packs/application.sass file: ```sass // ~ to tell that this is not a relative import @import '~bootstrap/dist/css/bootstrap' @import '~bootstrap/dist/css/bootstrap-theme' ``` ## Post-Processing CSS Webpacker out-of-the-box provides CSS post-processing using [postcss-loader](https://github.com/postcss/postcss-loader) and the installer sets up a standard `postcss.config.js` file in your app root with standard plugins. ```js module.exports = { plugins: [ require('postcss-import'), require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009' }, stage: 3 }) ] } ``` ## Using CSS with [vue-loader](https://github.com/vuejs/vue-loader) Vue templates require loading the stylesheet in your application in order for CSS to work. This is in addition to loading the JavaScript file for the entry point. Loading the stylesheet will also load the CSS for any nested components. ```erb <%= stylesheet_pack_tag 'hello_vue' %> <%= javascript_pack_tag 'hello_vue' %> ``` ## Resolve url loader Since `Sass/libsass` does not provide url rewriting, all linked assets must be relative to the output. Add the missing url rewriting using the resolve-url-loader. Place it directly after the sass-loader in the loader chain. ```bash yarn add resolve-url-loader ``` ```js // webpack/environment.js const { environment } = require('@rails/webpacker') // resolve-url-loader must be used before sass-loader environment.loaders.get('sass').use.splice(-1, 0, { loader: 'resolve-url-loader' }); module.exports = environment ``` ## Working with TypeScript In order to get CSS to work with typescript you have two options. You can either use `require` to bypass typescript special `import`. ```ts const styles = require('../hello_react/styles/hello-react'); ``` You may also use the package [typings-for-css-modules-loader](https://github.com/Jimdo/typings-for-css-modules-loader) instead of `css-loader` to automatically generate typescript `.d.ts` files in order to help resolve any css/scss styles. To do that: ```js // app/javascript/packs/hello_react.jsx import * as styles from '../hello_react.styles/hello-react.module.scss'; ``` ```bash yarn add --dev typings-for-css-modules-loader ``` ```js // webpack/environment.js const { environment } = require('@rails/webpacker') // replace css-loader with typings-for-css-modules-loader environment.loaders.get('moduleSass').use = environment.loaders.get('moduleSass').use.map((u) => { if(u.loader == 'css-loader') { return { ...u, loader: 'typings-for-css-modules-loader' }; } else { return u; } }); ``` webpacker-5.4.3/docs/env.md0000644000004100000410000000350714123265223015565 0ustar www-datawww-data# Environment variables Environment variables are supported out of the box in Webpacker. For example if you run the webpack dev server like so: ``` FOO=hello BAR=world ./bin/webpack-dev-server ``` You can then reference these variables in your JavaScript app code with `process.env`: ```js console.log(process.env.FOO) // Compiles to console.log("hello") ``` You may want to store configuration in environment variables via `.env` files, similar to the [dotenv Ruby gem](https://github.com/bkeepers/dotenv). In development, if you use [Foreman](http://ddollar.github.io/foreman) or [Invoker](http://invoker.codemancers.com) to launch the webpack server, both of these tools have basic support for a `.env` file (Invoker also supports `.env.local`), so no further configuration is needed. However, if you run the webpack server without Foreman/Invoker, or if you want more control over what `.env` files to load, you can use the [dotenv npm package](https://github.com/motdotla/dotenv). Here is what you could do to support a "Ruby-like" dotenv: ``` yarn add dotenv ``` ```javascript // config/webpack/environment.js ... const { environment } = require('@rails/webpacker') const webpack = require('webpack') const dotenv = require('dotenv') const dotenvFiles = [ `.env.${process.env.NODE_ENV}.local`, '.env.local', `.env.${process.env.NODE_ENV}`, '.env' ] dotenvFiles.forEach((dotenvFile) => { dotenv.config({ path: dotenvFile, silent: true }) }) module.exports = environment ``` **Warning:** using Foreman/Invoker and npm dotenv at the same time can result in confusing behavior, in that Foreman/Invoker variables take precedence over npm dotenv variables. If you'd like to pass custom variables to the on demand compiler, use `Webpacker::Compiler.env` attribute. ```rb Webpacker::Compiler.env['FRONTEND_API_KEY'] = 'your_secret_key' ``` webpacker-5.4.3/docs/docker.md0000644000004100000410000000323414123265223016241 0ustar www-datawww-data# Docker To setup webpacker with a dockerized Rails application. First, add a new service for webpacker in docker-compose.yml: ```Dockerfile version: '3' services: webpacker: build: . environment: - NODE_ENV=development - RAILS_ENV=development - WEBPACKER_DEV_SERVER_HOST=0.0.0.0 command: ./bin/webpack-dev-server volumes: - .:/webpacker-example-app ports: - '3035:3035' ``` add nodejs and yarn as dependencies in Dockerfile, ```dockerfile FROM ruby:2.4.1 RUN apt-get update -qq && apt-get install -y build-essential nodejs \ && rm -rf /var/lib/apt/lists/* \ && curl -o- -L https://yarnpkg.com/install.sh | bash # Rest of the commands.... ``` Please note: if using `assets:precompile` in the Dockerfile or have issues with the snippet above then try: ```dockerfile FROM ruby:2.4.1 RUN curl -sL https://deb.nodesource.com/setup_8.x | bash \ && apt-get update && apt-get install -y nodejs && rm -rf /var/lib/apt/lists/* \ && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \ && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \ && apt-get update && apt-get install -y yarn && rm -rf /var/lib/apt/lists/* # Rest of the commands.... ``` then add the webpacker host name environment variable to the web/app service: ```Dockerfile web: build: context: . command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - .:/usr/src/app ports: - "3000:3000" environment: - WEBPACKER_DEV_SERVER_HOST=webpacker ``` Lastly, rebuild your container: ```bash docker-compose up --build ``` webpacker-5.4.3/docs/webpack-dev-server.md0000644000004100000410000000554314123265223020473 0ustar www-datawww-data# webpack-dev-server ## HTTPS If you're using the `webpack-dev-server` in development, you can serve your packs over HTTPS by setting the `https` option for `webpack-dev-server` to `true` in `config/webpacker.yml`, then start the dev server as usual with `./bin/webpack-dev-server`. Please note that the `webpack-dev-server` will use a self-signed certificate, so your web browser will display a warning/exception upon accessing the page. If you get `https://localhost:3035/sockjs-node/info?t=1503127986584 net::ERR_INSECURE_RESPONSE` in your console, simply open the link in your browser and accept the SSL exception. Now if you refresh your Rails view everything should work as expected. ## HOT module replacement Webpacker out-of-the-box supports HMR with `webpack-dev-server` and you can toggle it by setting `dev_server/hmr` option inside `webpacker.yml`. Check out this guide for more information: - https://webpack.js.org/configuration/dev-server/#devserver-hot To support HMR with React you would need to add `react-hot-loader`. Checkout this guide for more information: - https://gaearon.github.io/react-hot-loader/getstarted/ **Note:** Don't forget to disable `HMR` if you are not running `webpack-dev-server` otherwise you will get not found error for stylesheets. ## Nginx If you use Nginx in development to proxy requests to your Rails server from another domain, like `myapp.dev`, the Webpacker middleware will be able to forward requests for "packs" to the webpack dev server. If you're using `inline` mode behind Nginx, you may also need to provide the hostname to webpack dev server so it can initiate the websocket connection for live reloading ([Webpack docs](https://webpack.js.org/configuration/dev-server/#devserver-public)). To do so, set the `public` option in `config/webpacker.yml`: ```yaml development: # ... dev_server: # ... public: myapp.dev ``` You may also need to add the following location block to your local Nginx server configuration for your Rails app. ``` server { listen 80; server_name myapp.dev # Proxy webpack dev server websocket requests location /sockjs-node { proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://127.0.0.1:3035; # change to match your webpack-dev-server host } # ... } ``` ## Customizing Logging By default, the dev server will display a colored progress notification while your code is being compiled. (Under the hood, we are using `webpack-dev-server --progress --color`). However, this might cause issues if you don't use `foreman` and/or try to log webpack-dev-server's output to a file. You can disable this stylized output by adding `pretty: false` to your `dev_server` config: ```yaml development: # ... dev_server: # ... pretty: false ``` webpacker-5.4.3/docs/yarn.md0000644000004100000410000000142514123265223015743 0ustar www-datawww-data# Yarn Webpacker by default uses `yarn` as a package manager for `node_modules` ## Add a new npm module To add any new JS module you can use `yarn`: ```bash yarn add bootstrap material-ui ``` ## Add an npm module to `devDependencies` To add a new JS module that will only be available to local development: ```bash yarn add --dev browser-sync ``` Be careful not to add any build or app related JS modules in this fashion. Adding JS modules to `devDependencies` [will block them from being installed in **any** production environment](https://yarnpkg.com/lang/en/docs/cli/install/#toc-yarn-install-production-true-false). Docs from JS modules may instruct you to use `--dev` or `devDependencies`, but this is generally under the assumption that you are using a `node.js` workflow. webpacker-5.4.3/docs/cloud9.md0000644000004100000410000002613414123265223016175 0ustar www-datawww-data# Webpack dev server and Rails on Cloud9 **Please note that this article is particularly relevant when migrating the [`webpacker`] gem from v3.0.1 to v3.0.2, as described in the [below](#binstub-versions).** [**`[Go to tl;dr]`**](#tldr) ## Contents - [Context](#context) - [Binstub versions](#binstub-versions) - [Quick solution](#quick-solution) - [Flexible solution](#flexible-solution) - [Sources](#sources) - [Versions](#versions) - [tl;dr](#tldr) ## Context This article describes how to properly configure [`webpack-dev-server`] with [`webpacker`] gem on a [Cloud9] workspace. After a preliminary remark about the proper binstub version of the `./bin/webpack-dev-server` script, this article presents two ways to tackle the task: a simple and [quick solution](#quick-solution), which is sufficient if we work alone on a project, and a slightly more involved but [flexible approach](#flexible-solution), that can be useful when several people might work in the same codebase. [Cloud9]: https://c9.io [`webpack-dev-server`]: https://github.com/webpack/webpack-dev-server [`webpacker`]: https://github.com/rails/webpacker ## Binstub versions A lot of the confusion about the [`webpack-dev-server`] options and why they might not be properly taken into account, might be due to an outdated version of the `./bin/webpack-dev-server` script. The script created by the `rails webpacker:install` task of the [`webpacker`] gem v3.0.1 ([source][v3.0.1/lib/install/bin/webpack-dev-server.tt]) is not compatible with how v3.0.2 (sic) of the gem handles the [`webpack-dev-server`] option flags (see full list of [versions](#versions) below), which logically expects the corresponding [binstub version][#833] of the script ([source][v3.0.2/exe/webpack-dev-server]). So please make sure that you are using the [correct binstub][v3.0.2/exe/webpack-dev-server] (the same applies to [`./bin/webpack`][v3.0.2/exe/webpack]). To be fair, the [changelog of v3.0.2] properly mentions the change: > - Added: Binstubs [#833] > - (...) > - Removed: Inline CLI args for dev server binstub, use env variables instead [changelog of v3.0.2]: https://github.com/rails/webpacker/blob/v3.0.2/CHANGELOG.md#302---2017-10-04 [v3.0.1/lib/install/bin/webpack-dev-server.tt]: https://github.com/rails/webpacker/blob/v3.0.1/lib/install/bin/webpack-dev-server.tt [v3.0.2/exe/webpack-dev-server]: https://github.com/rails/webpacker/blob/v3.0.2/exe/webpack-dev-server [v3.0.2/exe/webpack]: https://github.com/rails/webpacker/blob/v3.0.2/exe/webpack [#833]: https://github.com/rails/webpacker/pull/833/files ## Quick solution If you are working alone, the easiest way to fix the configuration of the [`webpack-dev-server`] is to modify the `development.dev_server` entry of the `config/webpacker.yml` file. ### `config/webpacker.yml` file The `development.dev_server` entry of the `config/webpacker.yml` file has to be changed from the following default values: ```yaml dev_server: https: false host: localhost port: 3035 public: localhost:3035 hmr: false # Inline should be set to true if using HMR inline: true overlay: true disable_host_check: true use_local_ip: false ``` into these custom configuration: ```yaml dev_server: https: true host: localhost port: 8082 public: your-workspace-name-yourusername.c9users.io:8082 hmr: false inline: false overlay: true disable_host_check: true use_local_ip: false ``` You can obtain the value `your-workspace-name-yourusername.c9users.io` for your [Cloud9] workspace with `echo ${C9_HOSTNAME}`. There are four main differences with the approaches found in the mentioned [sources](#sources): - Some solutions suggested to set the [`host`][devserver-host] option to `your-workspace-name-yourusername.c9users.io`, which required to add a line to the `/etc/hosts` file by running `echo "0.0.0.0 ${C9_HOSTNAME}" | sudo tee -a /etc/hosts`. This was only necessary due to restrictions in previous versions of [`webpacker`] and how the value of the [`public`][devserver-public] setting was calculated. Currently it is [no longer necessary][pr-comment-hosts] to modify the `/etc/hosts` file because the [`host`][devserver-host] setting can be kept as `localhost`. [pr-comment-hosts]: https://github.com/rails/webpacker/pull/1033#pullrequestreview-78992024 - Some solutions stressed the need to set the [`https`][devserver-https] option to `false` but this failed with `net::ERR_ABORTED` in the browser console and raised the following exception in the server when the client tried to get the JavaScript sources: ``` # ``` Setting `https: true` removes the issue. - By leaving the [`inline`][devserver-inline] option to the default `false` value, the live compilation still works but the browser console constantly reports the following error: ``` Failed to load https://your-workspace-name-yourusername.c9users.io:8082/sockjs-node/info?t=1511016561187: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://your-workspace-name-yourusername.c9users.io' is therefore not allowed access. The response had HTTP status code 503. ``` Setting `inline: false` removes the issue. - None of the solutions suggested to set the [`public`][devserver-public] option in the `config/webpacker.yml` file and some suggested to pass it to the `webpack-dev-server` command line. By setting it in the configuration file we don't need to care about it in the terminal. [devserver-host]: https://webpack.js.org/configuration/dev-server/#devserver-host [devserver-https]: https://webpack.js.org/configuration/dev-server/#devserver-https [devserver-inline]: https://webpack.js.org/configuration/dev-server/#devserver-inline [devserver-public]: https://webpack.js.org/configuration/dev-server/#devserver-public With this configuration, running as usual `./bin/webpack-dev-server` in one terminal and `./bin/rails s -b $IP -p $PORT` in another should work. ## Flexible solution The previous solution is useful and fast to implement, but if you are working with other people on the same repo it can be tricky to maintain the proper configuration in the `config/webpacker.yml` file. Moreover, the hostname of your [Cloud9] workspace is hardcoded, so that the configuration is not portable. A hint about another way to configure the `webpack-dev-server` can be found in the [README of this repo][`webpacker` documentation]: > You can use environment variables as options supported by > webpack-dev-server in the form `WEBPACKER_DEV_SERVER_