webpacker-4.2.2/0000755000175000017500000000000013712041056012505 5ustar pravipraviwebpacker-4.2.2/lib/0000755000175000017500000000000013712041056013253 5ustar pravipraviwebpacker-4.2.2/lib/webpacker.rb0000644000175000017500000000213013712041056015537 0ustar pravipravirequire "active_support/core_ext/module/attribute_accessors" require "active_support/core_ext/string/inquiry" require "active_support/logger" require "active_support/tagged_logging" module Webpacker extend self def instance=(instance) @instance = instance end def instance @instance ||= Webpacker::Instance.new end def with_node_env(env) original = ENV["NODE_ENV"] ENV["NODE_ENV"] = env yield ensure ENV["NODE_ENV"] = original end def ensure_log_goes_to_stdout old_logger = Webpacker.logger Webpacker.logger = ActiveSupport::Logger.new(STDOUT) yield ensure Webpacker.logger = old_logger end delegate :logger, :logger=, :env, to: :instance delegate :config, :compiler, :manifest, :commands, :dev_server, to: :instance delegate :bootstrap, :clean, :clobber, :compile, to: :commands end require "webpacker/instance" require "webpacker/env" require "webpacker/configuration" require "webpacker/manifest" require "webpacker/compiler" require "webpacker/commands" require "webpacker/dev_server" require "webpacker/railtie" if defined?(Rails) webpacker-4.2.2/lib/install/0000755000175000017500000000000013712041056014721 5ustar pravipraviwebpacker-4.2.2/lib/install/react.rb0000644000175000017500000000155713712041056016354 0ustar pravipravirequire "webpacker/configuration" require "fileutils" replace_babel_config = FileUtils.compare_file(Rails.root.join("babel.config.js"), "#{__dir__}/config/babel.config.js") say "Copying babel.config.js to app root directory" copy_file "#{__dir__}/examples/react/babel.config.js", "babel.config.js", force: replace_babel_config say "Copying react example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/react/hello_react.jsx", "#{Webpacker.config.source_entry_path}/hello_react.jsx" say "Updating webpack paths to include .jsx file extension" insert_into_file Webpacker.config.config_path, "- .jsx\n".indent(4), after: /\s+extensions:\n/ say "Installing all react dependencies" run "yarn add react react-dom @babel/preset-react prop-types babel-plugin-transform-react-remove-prop-types" say "Webpacker now supports react.js 🎉", :green webpacker-4.2.2/lib/install/svelte.rb0000644000175000017500000000231113712041056016545 0ustar pravipravirequire "webpacker/configuration" say "Copying svelte loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/svelte.js", Rails.root.join("config/webpack/loaders/svelte.js").to_s say "Adding svelte loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const svelte = require('./loaders/svelte')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('svelte', svelte)\n", before: "module.exports" say "Copying Svelte example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/svelte/hello_svelte.js", "#{Webpacker.config.source_entry_path}/hello_svelte.js" say "Copying Svelte app file to #{Webpacker.config.source_path}" copy_file "#{__dir__}/examples/svelte/app.svelte", "#{Webpacker.config.source_path}/app.svelte" say "Installing all Svelte dependencies" run "yarn add svelte svelte-loader" say "Updating webpack paths to include .svelte file extension" insert_into_file Webpacker.config.config_path, "- .svelte\n".indent(4), after: /\s+extensions:\n/ say "Webpacker now supports Svelte 🎉", :green webpacker-4.2.2/lib/install/erb.rb0000644000175000017500000000177713712041056016032 0ustar pravipravirequire "webpacker/configuration" say "Copying erb loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/erb.js", Rails.root.join("config/webpack/loaders/erb.js").to_s say "Adding erb loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const erb = require('./loaders/erb')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('erb', erb)\n", before: "module.exports" say "Updating webpack paths to include .erb file extension" insert_into_file Webpacker.config.config_path, "- .erb\n".indent(4), after: /\s+extensions:\n/ say "Copying the example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/erb/hello_erb.js.erb", "#{Webpacker.config.source_entry_path}/hello_erb.js.erb" say "Installing all Erb dependencies" run "yarn add rails-erb-loader" say "Webpacker now supports Erb in JS 🎉", :green webpacker-4.2.2/lib/install/binstubs.rb0000644000175000017500000000015213712041056017075 0ustar pravipravisay "Copying binstubs" directory "#{__dir__}/bin", "bin" chmod "bin", 0755 & ~File.umask, verbose: false webpacker-4.2.2/lib/install/examples/0000755000175000017500000000000013712041056016537 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/vue/0000755000175000017500000000000013712041056017336 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/vue/app.vue0000644000175000017500000000040113712041056020632 0ustar pravipravi webpacker-4.2.2/lib/install/examples/vue/hello_vue.js0000644000175000017500000000355013712041056021661 0ustar pravipravi/* eslint no-console: 0 */ // Run this example by adding <%= javascript_pack_tag 'hello_vue' %> (and // <%= stylesheet_pack_tag 'hello_vue' %> if you have styles in your component) // to the head of your layout file, // like app/views/layouts/application.html.erb. // All it does is render
Hello Vue
at the bottom of the page. import Vue from 'vue' import App from '../app.vue' document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ render: h => h(App) }).$mount() document.body.appendChild(app.$el) console.log(app) }) // The above code uses Vue without the compiler, which means you cannot // use Vue to target elements in your existing html templates. You would // need to always use single file components. // To be able to target elements in your existing html/erb templates, // comment out the above code and uncomment the below // Add <%= javascript_pack_tag 'hello_vue' %> to your layout // Then add this markup to your html template: // //
// {{message}} // //
// import Vue from 'vue/dist/vue.esm' // import App from '../app.vue' // // document.addEventListener('DOMContentLoaded', () => { // const app = new Vue({ // el: '#hello', // data: { // message: "Can you say hello?" // }, // components: { App } // }) // }) // // // // If the project is using turbolinks, install 'vue-turbolinks': // // yarn add vue-turbolinks // // Then uncomment the code block below: // // import TurbolinksAdapter from 'vue-turbolinks' // import Vue from 'vue/dist/vue.esm' // import App from '../app.vue' // // Vue.use(TurbolinksAdapter) // // document.addEventListener('turbolinks:load', () => { // const app = new Vue({ // el: '#hello', // data: () => { // return { // message: "Can you say hello?" // } // }, // components: { App } // }) // }) webpacker-4.2.2/lib/install/examples/coffee/0000755000175000017500000000000013712041056017766 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/coffee/hello_coffee.coffee0000644000175000017500000000030413712041056023546 0ustar pravipravi# Run this example by adding <%= javascript_pack_tag 'hello_coffee' %> to the head of your layout file, # like app/views/layouts/application.html.erb. console.log 'Hello world from coffeescript' webpacker-4.2.2/lib/install/examples/typescript/0000755000175000017500000000000013712041056020745 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/typescript/tsconfig.json0000644000175000017500000000071213712041056023454 0ustar pravipravi{ "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es6", "dom"], "module": "es6", "moduleResolution": "node", "baseUrl": ".", "paths": { "*": ["node_modules/*", "app/javascript/*"] }, "sourceMap": true, "target": "es5" }, "exclude": [ "**/*.spec.ts", "node_modules", "vendor", "public" ], "compileOnSave": false } webpacker-4.2.2/lib/install/examples/typescript/hello_typescript.ts0000644000175000017500000000031213712041056024702 0ustar pravipravi// Run this example by adding <%= javascript_pack_tag 'hello_typescript' %> to the head of your layout file, // like app/views/layouts/application.html.erb. console.log('Hello world from typescript'); webpacker-4.2.2/lib/install/examples/react/0000755000175000017500000000000013712041056017635 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/react/tsconfig.json0000644000175000017500000000060013712041056022340 0ustar pravipravi{ "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es6", "dom"], "module": "es6", "moduleResolution": "node", "sourceMap": true, "target": "es5", "jsx": "react" }, "exclude": [ "**/*.spec.ts", "node_modules", "vendor", "public" ], "compileOnSave": false } webpacker-4.2.2/lib/install/examples/react/babel.config.js0000644000175000017500000000403513712041056022506 0ustar pravipravimodule.exports = function(api) { var validEnv = ['development', 'test', 'production'] var currentEnv = api.env() var isDevelopmentEnv = api.env('development') var isProductionEnv = api.env('production') var isTestEnv = api.env('test') if (!validEnv.includes(currentEnv)) { throw new Error( 'Please specify a valid `NODE_ENV` or ' + '`BABEL_ENV` environment variables. Valid values are "development", ' + '"test", and "production". Instead, received: ' + JSON.stringify(currentEnv) + '.' ) } return { presets: [ isTestEnv && [ '@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }, '@babel/preset-react' ], (isProductionEnv || isDevelopmentEnv) && [ '@babel/preset-env', { forceAllTransforms: true, useBuiltIns: 'entry', corejs: 3, modules: false, exclude: ['transform-typeof-symbol'] } ], [ '@babel/preset-react', { development: isDevelopmentEnv || isTestEnv, useBuiltIns: true } ] ].filter(Boolean), plugins: [ 'babel-plugin-macros', '@babel/plugin-syntax-dynamic-import', isTestEnv && 'babel-plugin-dynamic-import-node', '@babel/plugin-transform-destructuring', [ '@babel/plugin-proposal-class-properties', { loose: true } ], [ '@babel/plugin-proposal-object-rest-spread', { useBuiltIns: true } ], [ '@babel/plugin-transform-runtime', { helpers: false, regenerator: true, corejs: false } ], [ '@babel/plugin-transform-regenerator', { async: false } ], isProductionEnv && [ 'babel-plugin-transform-react-remove-prop-types', { removeImport: true } ] ].filter(Boolean) } } webpacker-4.2.2/lib/install/examples/react/hello_react.jsx0000644000175000017500000000120413712041056022641 0ustar pravipravi// Run this example by adding <%= javascript_pack_tag 'hello_react' %> to the head of your layout file, // like app/views/layouts/application.html.erb. All it does is render
Hello React
at the bottom // of the page. import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' const Hello = props => (
Hello {props.name}!
) Hello.defaultProps = { name: 'David' } Hello.propTypes = { name: PropTypes.string } document.addEventListener('DOMContentLoaded', () => { ReactDOM.render( , document.body.appendChild(document.createElement('div')), ) }) webpacker-4.2.2/lib/install/examples/elm/0000755000175000017500000000000013712041056017314 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/elm/hello_elm.js0000644000175000017500000000063513712041056021616 0ustar pravipravi// Run this example by adding <%= javascript_pack_tag "hello_elm" %> to the // head of your layout file, like app/views/layouts/application.html.erb. // It will render "Hello Elm!" within the page. import { Elm } from '../Main' document.addEventListener('DOMContentLoaded', () => { const target = document.createElement('div') document.body.appendChild(target) Elm.Main.init({ node: target }) }) webpacker-4.2.2/lib/install/examples/elm/Main.elm0000644000175000017500000000171713712041056020705 0ustar pravipravimodule Main exposing (..) import Browser import Html exposing (Html, h1, text) import Html.Attributes exposing (style) -- MODEL type alias Model = { } -- INIT init : (Model, Cmd Message) init = (Model, Cmd.none) -- VIEW view : Model -> Html Message view model = -- The inline style is being used for example purposes in order to keep this example simple and -- avoid loading additional resources. Use a proper stylesheet when building your own app. h1 [style "display" "flex", style "justify-content" "center"] [text "Hello Elm!"] -- MESSAGE type Message = None -- UPDATE update : Message -> Model -> (Model, Cmd Message) update message model = (model, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Message subscriptions model = Sub.none -- MAIN main : Program (Maybe {}) Model Message main = Browser.element { init = always init, view = view, update = update, subscriptions = subscriptions } webpacker-4.2.2/lib/install/examples/stimulus/0000755000175000017500000000000013712041056020424 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/stimulus/application.js0000644000175000017500000000002513712041056023262 0ustar pravipraviimport "controllers" webpacker-4.2.2/lib/install/examples/stimulus/controllers/0000755000175000017500000000000013712041056022772 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/stimulus/controllers/index.js0000644000175000017500000000061413712041056024440 0ustar pravipravi// Load all the controllers within this directory and all subdirectories. // Controller files must be named *_controller.js. import { Application } from "stimulus" import { definitionsFromContext } from "stimulus/webpack-helpers" const application = Application.start() const context = require.context("controllers", true, /_controller\.js$/) application.load(definitionsFromContext(context)) webpacker-4.2.2/lib/install/examples/stimulus/controllers/hello_controller.js0000644000175000017500000000070013712041056026673 0ustar pravipravi// Visit The Stimulus Handbook for more details // https://stimulusjs.org/handbook/introduction // // This example controller works with specially annotated HTML like: // //
//

//
import { Controller } from "stimulus" export default class extends Controller { static targets = [ "output" ] connect() { this.outputTarget.textContent = 'Hello, Stimulus!' } } webpacker-4.2.2/lib/install/examples/angular/0000755000175000017500000000000013712041056020170 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/angular/hello_angular.js0000644000175000017500000000031413712041056023340 0ustar pravipravi// Run this Angular example by adding the following HTML markup to your view: // // Loading... // // <%= javascript_pack_tag 'hello_angular' %> require('../hello_angular') webpacker-4.2.2/lib/install/examples/angular/hello_angular/0000755000175000017500000000000013712041056023004 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/angular/hello_angular/app/0000755000175000017500000000000013712041056023564 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/angular/hello_angular/app/app.component.ts0000644000175000017500000000026213712041056026715 0ustar pravipraviimport { Component } from '@angular/core'; @Component({ selector: 'hello-angular', template: `

Hello {{name}}

` }) export class AppComponent { name = 'Angular!'; } webpacker-4.2.2/lib/install/examples/angular/hello_angular/app/app.module.ts0000644000175000017500000000047213712041056026203 0ustar pravipraviimport { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } webpacker-4.2.2/lib/install/examples/angular/hello_angular/polyfills.ts0000644000175000017500000000476113712041056025401 0ustar pravipravi/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE9, IE10 and IE11 requires all of the following polyfills. **/ // import 'core-js/es6/symbol'; // import 'core-js/es6/object'; // import 'core-js/es6/function'; // import 'core-js/es6/parse-int'; // import 'core-js/es6/parse-float'; // import 'core-js/es6/number'; // import 'core-js/es6/math'; // import 'core-js/es6/string'; // import 'core-js/es6/date'; // import 'core-js/es6/array'; // import 'core-js/es6/regexp'; // import 'core-js/es6/map'; // import 'core-js/es6/weak-map'; // import 'core-js/es6/set'; /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** Evergreen browsers require these. **/ import 'core-js/es/reflect'; import 'core-js/proposals/reflect-metadata'; /** * Required to support Web Animations `@angular/animation`. * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation **/ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /*************************************************************************************************** * Zone JS is required by Angular itself. */ import 'zone.js/dist/zone'; // import 'zone.js/dist/long-stack-trace-zone' // async stack traces with zone.js /*************************************************************************************************** * APPLICATION IMPORTS */ /** * Date, currency, decimal and percent pipes. * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 */ // import 'intl'; // Run `npm install --save intl`. /** * Need to import at least one locale-data with intl. */ // import 'intl/locale-data/jsonp/en'; webpacker-4.2.2/lib/install/examples/angular/hello_angular/index.ts0000644000175000017500000000040613712041056024463 0ustar pravipraviimport './polyfills.ts'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; document.addEventListener('DOMContentLoaded', () => { platformBrowserDynamic().bootstrapModule(AppModule); }); webpacker-4.2.2/lib/install/examples/svelte/0000755000175000017500000000000013712041056020041 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/svelte/app.svelte0000644000175000017500000000015613712041056022047 0ustar pravipravi

Hello {name}!

webpacker-4.2.2/lib/install/examples/svelte/hello_svelte.js0000644000175000017500000000105613712041056023066 0ustar pravipravi/* eslint no-console: 0 */ // Run this example by adding <%= javascript_pack_tag 'hello_svelte' %> (and // <%= stylesheet_pack_tag 'hello_svelte' %> if you have styles in your component) // to the head of your layout file, // like app/views/layouts/application.html.erb. // All it does is render
Hello Svelte!
at the bottom of the page. import App from '../app.svelte' document.addEventListener('DOMContentLoaded', () => { const app = new App({ target: document.body, props: { name: 'Svelte' } }); window.app = app; }) webpacker-4.2.2/lib/install/examples/erb/0000755000175000017500000000000013712041056017307 5ustar pravipraviwebpacker-4.2.2/lib/install/examples/erb/hello_erb.js.erb0000644000175000017500000000043713712041056022353 0ustar pravipravi// Run this example by adding <%%= javascript_pack_tag 'hello_erb' %> to the head of your layout file, // like app/views/layouts/application.html.erb. Don't forget to uncomment erb tag after adding it to your layout file. <% name = 'Erb' %> console.log('Hello world from <%= name %>') webpacker-4.2.2/lib/install/typescript.rb0000644000175000017500000000350113712041056017453 0ustar pravipravirequire "webpacker/configuration" additional_packages = "" example_source = "typescript" # Additional configuration is required for React projects package_json = Rails.root.join("package.json") if File.exist?(package_json) package = JSON.parse(File.read(package_json)) package["dependencies"] ||= {} if package["dependencies"].keys.include?("react") additional_packages = "@types/react @types/react-dom" example_source = "react" end end say "Copying typescript loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/typescript.js", Rails.root.join("config/webpack/loaders/typescript.js").to_s say "Adding typescript loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const typescript = require('./loaders/typescript')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('typescript', typescript)\n", before: "module.exports" say "Copying tsconfig.json to the Rails root directory for typescript" copy_file "#{__dir__}/examples/#{example_source}/tsconfig.json", "tsconfig.json" say "Updating webpack paths to include .ts file extension" insert_into_file Webpacker.config.config_path, "- .ts\n".indent(4), after: /\s+extensions:\n/ say "Updating webpack paths to include .tsx file extension" insert_into_file Webpacker.config.config_path, "- .tsx\n".indent(4), after: /\s+extensions:\n/ say "Copying the example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/typescript/hello_typescript.ts", "#{Webpacker.config.source_entry_path}/hello_typescript.ts" say "Installing all typescript dependencies" run "yarn add typescript ts-loader #{additional_packages}" say "Webpacker now supports typescript 🎉", :green webpacker-4.2.2/lib/install/template.rb0000644000175000017500000000372313712041056017066 0ustar pravipravi# Install Webpacker copy_file "#{__dir__}/config/webpacker.yml", "config/webpacker.yml" puts "Copying webpack core config" directory "#{__dir__}/config/webpack", "config/webpack" say "Copying postcss.config.js to app root directory" copy_file "#{__dir__}/config/postcss.config.js", "postcss.config.js" say "Copying babel.config.js to app root directory" copy_file "#{__dir__}/config/babel.config.js", "babel.config.js" say "Copying .browserslistrc to app root directory" copy_file "#{__dir__}/config/.browserslistrc", ".browserslistrc" if Dir.exists?(Webpacker.config.source_path) say "The JavaScript app source directory already exists" else say "Creating JavaScript app source directory" directory "#{__dir__}/javascript", Webpacker.config.source_path end apply "#{__dir__}/binstubs.rb" if File.exists?(".gitignore") append_to_file ".gitignore" do "\n" + "/public/packs\n" + "/public/packs-test\n" + "/node_modules\n" + "/yarn-error.log\n" + "yarn-debug.log*\n" + ".yarn-integrity\n" end end if Webpacker::VERSION =~ /^[0-9]+\.[0-9]+\.[0-9]+$/ say "Installing all JavaScript dependencies [#{Webpacker::VERSION}]" run "yarn add @rails/webpacker@#{Webpacker::VERSION}" else say "Installing all JavaScript dependencies [from prerelease rails/webpacker]" run "yarn add @rails/webpacker@next" end say "Installing dev server for live reloading" run "yarn add --dev webpack-dev-server" if Rails::VERSION::MAJOR == 5 && Rails::VERSION::MINOR > 1 say "You need to allow webpack-dev-server host as allowed origin for connect-src.", :yellow say "This can be done in Rails 5.2+ for development environment in the CSP initializer", :yellow say "config/initializers/content_security_policy.rb with a snippet like this:", :yellow say "policy.connect_src :self, :https, \"http://localhost:3035\", \"ws://localhost:3035\" if Rails.env.development?", :yellow end say "Webpacker successfully installed 🎉 🍰", :green webpacker-4.2.2/lib/install/loaders/0000755000175000017500000000000013712041056016352 5ustar pravipraviwebpacker-4.2.2/lib/install/loaders/erb.js0000644000175000017500000000035213712041056017460 0ustar pravipravimodule.exports = { test: /\.erb$/, enforce: 'pre', exclude: /node_modules/, use: [{ loader: 'rails-erb-loader', options: { runner: (/^win/.test(process.platform) ? 'ruby ' : '') + 'bin/rails runner' } }] } webpacker-4.2.2/lib/install/loaders/typescript.js0000644000175000017500000000031613712041056021116 0ustar pravipraviconst PnpWebpackPlugin = require('pnp-webpack-plugin') module.exports = { test: /\.tsx?(\.erb)?$/, use: [ { loader: 'ts-loader', options: PnpWebpackPlugin.tsLoaderOptions() } ] } webpacker-4.2.2/lib/install/loaders/elm.js0000644000175000017500000000123513712041056017466 0ustar pravipraviconst { resolve } = require('path') const isProduction = process.env.NODE_ENV === 'production' const isDevelopment = process.env.NODE_ENV === 'development' const elmSource = resolve(process.cwd()) const elmBinary = `${elmSource}/node_modules/.bin/elm` const options = { cwd: elmSource, pathToElm: elmBinary, optimize: isProduction, verbose: isDevelopment, debug: isDevelopment } const elmWebpackLoader = { loader: 'elm-webpack-loader', options: options } module.exports = { test: /\.elm(\.erb)?$/, exclude: [/elm-stuff/, /node_modules/], use: isProduction ? [elmWebpackLoader] : [{ loader: 'elm-hot-webpack-loader' }, elmWebpackLoader] } webpacker-4.2.2/lib/install/loaders/vue.js0000644000175000017500000000012713712041056017507 0ustar pravipravimodule.exports = { test: /\.vue(\.erb)?$/, use: [{ loader: 'vue-loader' }] } webpacker-4.2.2/lib/install/loaders/coffee.js0000644000175000017500000000013513712041056020136 0ustar pravipravimodule.exports = { test: /\.coffee(\.erb)?$/, use: [{ loader: 'coffee-loader' }] } webpacker-4.2.2/lib/install/loaders/svelte.js0000644000175000017500000000020213712041056020204 0ustar pravipravimodule.exports = { test: /\.svelte$/, use: [{ loader: 'svelte-loader', options: { hotReload: true } }], } webpacker-4.2.2/lib/install/coffee.rb0000644000175000017500000000210413712041056016472 0ustar pravipravirequire "webpacker/configuration" say "Copying coffee loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/coffee.js", Rails.root.join("config/webpack/loaders/coffee.js").to_s say "Adding coffee loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const coffee = require('./loaders/coffee')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('coffee', coffee)\n", before: "module.exports" say "Updating webpack paths to include .coffee file extension" insert_into_file Webpacker.config.config_path, "- .coffee\n".indent(4), after: /\s+extensions:\n/ say "Copying the example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/coffee/hello_coffee.coffee", "#{Webpacker.config.source_entry_path}/hello_coffee.coffee" say "Installing all Coffeescript dependencies" run "yarn add coffeescript@1.12.7 coffee-loader" say "Webpacker now supports Coffeescript 🎉", :green webpacker-4.2.2/lib/install/stimulus.rb0000644000175000017500000000076013712041056017136 0ustar pravipravisay "Appending Stimulus setup code to #{Webpacker.config.source_entry_path}/application.js" append_to_file "#{Webpacker.config.source_entry_path}/application.js" do "\n" + open("#{__dir__}/examples/stimulus/application.js").read end say "Creating controllers directory" directory "#{__dir__}/examples/stimulus/controllers", "#{Webpacker.config.source_path}/controllers" say "Installing all Stimulus dependencies" run "yarn add stimulus" say "Webpacker now supports Stimulus.js 🎉", :green webpacker-4.2.2/lib/install/javascript/0000755000175000017500000000000013712041056017067 5ustar pravipraviwebpacker-4.2.2/lib/install/javascript/packs/0000755000175000017500000000000013712041056020170 5ustar pravipraviwebpacker-4.2.2/lib/install/javascript/packs/application.js0000644000175000017500000000152013712041056023027 0ustar pravipravi/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb // Uncomment to copy all static images under ../images to the output folder and reference // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) // or the `imagePath` JavaScript helper below. // // const images = require.context('../images', true) // const imagePath = (name) => images(name, true) console.log('Hello World from Webpacker') webpacker-4.2.2/lib/install/vue.rb0000644000175000017500000000407113712041056016047 0ustar pravipravirequire "webpacker/configuration" say "Copying vue loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/vue.js", Rails.root.join("config/webpack/loaders/vue.js").to_s say "Adding vue loader plugin to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const { VueLoaderPlugin } = require('vue-loader')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())\n", before: "module.exports" say "Adding vue loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const vue = require('./loaders/vue')\n", after: "require('vue-loader')\n" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('vue', vue)\n", before: "module.exports" say "Updating webpack paths to include .vue file extension" insert_into_file Webpacker.config.config_path, "- .vue\n".indent(4), after: /\s+extensions:\n/ say "Copying the example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/vue/hello_vue.js", "#{Webpacker.config.source_entry_path}/hello_vue.js" say "Copying Vue app file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/vue/app.vue", "#{Webpacker.config.source_path}/app.vue" say "Installing all Vue dependencies" run "yarn add vue vue-loader vue-template-compiler" if Rails::VERSION::MAJOR == 5 && Rails::VERSION::MINOR > 1 say "You need to enable unsafe-eval rule.", :yellow say "This can be done in Rails 5.2+ for development environment in the CSP initializer", :yellow say "config/initializers/content_security_policy.rb with a snippet like this:", :yellow say "if Rails.env.development?", :yellow say " policy.script_src :self, :https, :unsafe_eval", :yellow say "else", :yellow say " policy.script_src :self, :https", :yellow say "end", :yellow end say "Webpacker now supports Vue.js 🎉", :green webpacker-4.2.2/lib/install/bin/0000755000175000017500000000000013712041056015471 5ustar pravipraviwebpacker-4.2.2/lib/install/bin/webpack-dev-server0000755000175000017500000000064313712041056021116 0ustar pravipravi#!/usr/bin/env ruby ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" ENV["NODE_ENV"] ||= "development" require "pathname" ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", Pathname.new(__FILE__).realpath) require "bundler/setup" require "webpacker" require "webpacker/dev_server_runner" APP_ROOT = File.expand_path("..", __dir__) Dir.chdir(APP_ROOT) do Webpacker::DevServerRunner.run(ARGV) end webpacker-4.2.2/lib/install/bin/webpack0000755000175000017500000000063613712041056017040 0ustar pravipravi#!/usr/bin/env ruby ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" ENV["NODE_ENV"] ||= "development" require "pathname" ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", Pathname.new(__FILE__).realpath) require "bundler/setup" require "webpacker" require "webpacker/webpack_runner" APP_ROOT = File.expand_path("..", __dir__) Dir.chdir(APP_ROOT) do Webpacker::WebpackRunner.run(ARGV) end webpacker-4.2.2/lib/install/config/0000755000175000017500000000000013712041056016166 5ustar pravipraviwebpacker-4.2.2/lib/install/config/babel.config.js0000644000175000017500000000327213712041056021041 0ustar pravipravimodule.exports = function(api) { var validEnv = ['development', 'test', 'production'] var currentEnv = api.env() var isDevelopmentEnv = api.env('development') var isProductionEnv = api.env('production') var isTestEnv = api.env('test') if (!validEnv.includes(currentEnv)) { throw new Error( 'Please specify a valid `NODE_ENV` or ' + '`BABEL_ENV` environment variables. Valid values are "development", ' + '"test", and "production". Instead, received: ' + JSON.stringify(currentEnv) + '.' ) } return { presets: [ isTestEnv && [ '@babel/preset-env', { targets: { node: 'current' } } ], (isProductionEnv || isDevelopmentEnv) && [ '@babel/preset-env', { forceAllTransforms: true, useBuiltIns: 'entry', corejs: 3, modules: false, exclude: ['transform-typeof-symbol'] } ] ].filter(Boolean), plugins: [ 'babel-plugin-macros', '@babel/plugin-syntax-dynamic-import', isTestEnv && 'babel-plugin-dynamic-import-node', '@babel/plugin-transform-destructuring', [ '@babel/plugin-proposal-class-properties', { loose: true } ], [ '@babel/plugin-proposal-object-rest-spread', { useBuiltIns: true } ], [ '@babel/plugin-transform-runtime', { helpers: false, regenerator: true, corejs: false } ], [ '@babel/plugin-transform-regenerator', { async: false } ] ].filter(Boolean) } } webpacker-4.2.2/lib/install/config/.browserslistrc0000644000175000017500000000001113712041056021246 0ustar pravipravidefaults webpacker-4.2.2/lib/install/config/webpacker.yml0000644000175000017500000000364213712041056020661 0ustar pravipravi# Note: You must restart bin/webpack-dev-server for changes to take effect default: &default source_path: app/javascript source_entry_path: packs public_root_path: public public_output_path: packs cache_path: tmp/cache/webpacker check_yarn_integrity: false webpack_compile_output: true # Additional paths webpack should lookup modules # ['app/assets', 'engine/foo/app/assets'] resolved_paths: [] # Reload manifest.json on all requests so we reload latest compiled packs cache_manifest: false # Extract and emit a css file extract_css: false static_assets_extensions: - .jpg - .jpeg - .png - .gif - .tiff - .ico - .svg - .eot - .otf - .ttf - .woff - .woff2 extensions: - .mjs - .js - .sass - .scss - .css - .module.sass - .module.scss - .module.css - .png - .svg - .gif - .jpeg - .jpg development: <<: *default compile: true # Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules check_yarn_integrity: true # Reference: https://webpack.js.org/configuration/dev-server/ 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 compress: true disable_host_check: true use_local_ip: false quiet: false pretty: false headers: 'Access-Control-Allow-Origin': '*' watch_options: ignored: '**/node_modules/**' test: <<: *default compile: true # Compile test packs to a separate directory public_output_path: packs-test production: <<: *default # Production depends on precompilation of packs prior to booting for performance. compile: false # Extract and emit a css file extract_css: true # Cache manifest.json for performance cache_manifest: true webpacker-4.2.2/lib/install/config/webpack/0000755000175000017500000000000013712041056017602 5ustar pravipraviwebpacker-4.2.2/lib/install/config/webpack/environment.js0000644000175000017500000000012213712041056022477 0ustar pravipraviconst { environment } = require('@rails/webpacker') module.exports = environment webpacker-4.2.2/lib/install/config/webpack/production.js0000644000175000017500000000023213712041056022323 0ustar pravipraviprocess.env.NODE_ENV = process.env.NODE_ENV || 'production' const environment = require('./environment') module.exports = environment.toWebpackConfig() webpacker-4.2.2/lib/install/config/webpack/development.js0000644000175000017500000000023313712041056022460 0ustar pravipraviprocess.env.NODE_ENV = process.env.NODE_ENV || 'development' const environment = require('./environment') module.exports = environment.toWebpackConfig() webpacker-4.2.2/lib/install/config/webpack/test.js0000644000175000017500000000023313712041056021115 0ustar pravipraviprocess.env.NODE_ENV = process.env.NODE_ENV || 'development' const environment = require('./environment') module.exports = environment.toWebpackConfig() webpacker-4.2.2/lib/install/config/postcss.config.js0000644000175000017500000000034013712041056021463 0ustar pravipravimodule.exports = { plugins: [ require('postcss-import'), require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009' }, stage: 3 }) ] } webpacker-4.2.2/lib/install/angular.rb0000644000175000017500000000217613712041056016705 0ustar pravipravirequire "webpacker/configuration" say "Copying angular example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/angular/hello_angular.js", "#{Webpacker.config.source_entry_path}/hello_angular.js" say "Copying hello_angular app to #{Webpacker.config.source_path}" directory "#{__dir__}/examples/angular/hello_angular", "#{Webpacker.config.source_path}/hello_angular" say "Installing all angular dependencies" run "yarn add core-js zone.js rxjs @angular/core @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic" if Rails::VERSION::MAJOR == 5 && Rails::VERSION::MINOR > 1 say "You need to enable unsafe-eval rule.", :yellow say "This can be done in Rails 5.2+ for development environment in the CSP initializer", :yellow say "config/initializers/content_security_policy.rb with a snippet like this:", :yellow say "if Rails.env.development?", :yellow say " policy.script_src :self, :https, :unsafe_eval", :yellow say "else", :yellow say " policy.script_src :self, :https", :yellow say "end", :yellow end say "Webpacker now supports angular 🎉", :green webpacker-4.2.2/lib/install/elm.rb0000644000175000017500000000304613712041056016026 0ustar pravipravirequire "webpacker/configuration" say "Copying elm loader to config/webpack/loaders" copy_file "#{__dir__}/loaders/elm.js", Rails.root.join("config/webpack/loaders/elm.js").to_s say "Adding elm loader to config/webpack/environment.js" insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "const elm = require('./loaders/elm')\n", after: /require\(('|")@rails\/webpacker\1\);?\n/ insert_into_file Rails.root.join("config/webpack/environment.js").to_s, "environment.loaders.prepend('elm', elm)\n", before: "module.exports" say "Copying Elm example entry file to #{Webpacker.config.source_entry_path}" copy_file "#{__dir__}/examples/elm/hello_elm.js", "#{Webpacker.config.source_entry_path}/hello_elm.js" say "Copying Elm app file to #{Webpacker.config.source_path}" copy_file "#{__dir__}/examples/elm/Main.elm", "#{Webpacker.config.source_path}/Main.elm" say "Installing all Elm dependencies" run "yarn add elm elm-webpack-loader" run "yarn add --dev elm-hot-webpack-loader" run "yarn run elm init" run "yarn run elm make #{Webpacker.config.source_path}/Main.elm" say "Updating webpack paths to include .elm file extension" insert_into_file Webpacker.config.config_path, "- .elm\n".indent(4), after: /\s+extensions:\n/ say "Updating Elm source location" gsub_file "elm.json", /\"src\"\n/, %("#{Webpacker.config.source_path.relative_path_from(Rails.root)}"\n) say "Updating .gitignore to include elm-stuff folder" insert_into_file ".gitignore", "/elm-stuff\n", before: "/node_modules\n" say "Webpacker now supports Elm 🎉", :green webpacker-4.2.2/lib/webpacker/0000755000175000017500000000000013712041056015216 5ustar pravipraviwebpacker-4.2.2/lib/webpacker/dev_server.rb0000644000175000017500000000213213712041056017705 0ustar pravipraviclass Webpacker::DevServer DEFAULT_ENV_PREFIX = "WEBPACKER_DEV_SERVER".freeze # Configure dev server connection timeout (in seconds), default: 0.01 # Webpacker.dev_server.connect_timeout = 1 cattr_accessor(:connect_timeout) { 0.01 } attr_reader :config def initialize(config) @config = config end def running? if config.dev_server.present? Socket.tcp(host, port, connect_timeout: connect_timeout).close true else false end rescue false end def host fetch(:host) end def port fetch(:port) end def https? case fetch(:https) when true, "true", Hash true else false end end def protocol https? ? "https" : "http" end def host_with_port "#{host}:#{port}" end def pretty? fetch(:pretty) end def env_prefix config.dev_server.fetch(:env_prefix, DEFAULT_ENV_PREFIX) end private def fetch(key) ENV["#{env_prefix}_#{key.upcase}"] || config.dev_server.fetch(key, defaults[key]) end def defaults config.send(:defaults)[:dev_server] || {} end end webpacker-4.2.2/lib/webpacker/railtie.rb0000644000175000017500000000610713712041056017200 0ustar pravipravirequire "rails/railtie" require "webpacker/helper" require "webpacker/dev_server_proxy" class Webpacker::Engine < ::Rails::Engine # Allows Webpacker config values to be set via Rails env config files config.webpacker = ActiveSupport::OrderedOptions.new initializer "webpacker.set_configs" do |app| if app.config.webpacker.key?(:check_yarn_integrity) Webpacker.config.check_yarn_integrity = app.config.webpacker.check_yarn_integrity end end # ================================ # Check Yarn Integrity Initializer # ================================ # # development (on by default): # # to turn off: # - edit config/environments/development.rb # - add `config.webpacker.check_yarn_integrity = false` # # production (off by default): # # to turn on: # - edit config/environments/production.rb # - add `config.webpacker.check_yarn_integrity = true` initializer "webpacker.yarn_check" do |app| if File.exist?("yarn.lock") && Webpacker.config.config_path.exist? && Webpacker.config.check_yarn_integrity? output = `yarn check --integrity && yarn check --verify-tree 2>&1` unless $?.success? $stderr.puts "\n\n" $stderr.puts "========================================" $stderr.puts " Your Yarn packages are out of date!" $stderr.puts " Please run `yarn install --check-files` to update." $stderr.puts "========================================" $stderr.puts "\n\n" $stderr.puts "To disable this check, please change `check_yarn_integrity`" $stderr.puts "to `false` in your webpacker config file (config/webpacker.yml)." $stderr.puts "\n\n" $stderr.puts output $stderr.puts "\n\n" exit(1) end end end initializer "webpacker.proxy" do |app| insert_middleware = Webpacker.config.dev_server.present? rescue nil if insert_middleware app.middleware.insert_before 0, Rails::VERSION::MAJOR >= 5 ? Webpacker::DevServerProxy : "Webpacker::DevServerProxy", ssl_verify_none: true end end initializer "webpacker.helper" do ActiveSupport.on_load :action_controller do ActionController::Base.helper Webpacker::Helper end ActiveSupport.on_load :action_view do include Webpacker::Helper end end initializer "webpacker.logger" do config.after_initialize do if ::Rails.logger.respond_to?(:tagged) Webpacker.logger = ::Rails.logger else Webpacker.logger = ActiveSupport::TaggedLogging.new(::Rails.logger) end end end initializer "webpacker.bootstrap" do if defined?(Rails::Server) || defined?(Rails::Console) Webpacker.bootstrap if defined?(Spring) require "spring/watcher" Spring.after_fork { Webpacker.bootstrap } Spring.watch(Webpacker.config.config_path) end end end initializer "webpacker.set_source" do |app| if Webpacker.config.config_path.exist? app.config.javascript_path = Webpacker.config.source_path.relative_path_from(Rails.root.join("app")).to_s end end end webpacker-4.2.2/lib/webpacker/configuration.rb0000644000175000017500000000453713712041056020423 0ustar pravipravirequire "yaml" require "active_support/core_ext/hash/keys" require "active_support/core_ext/hash/indifferent_access" class Webpacker::Configuration attr_reader :root_path, :config_path, :env def initialize(root_path:, config_path:, env:) @root_path = root_path @config_path = config_path @env = env end def dev_server fetch(:dev_server) end def compile? fetch(:compile) end def source_path root_path.join(fetch(:source_path)) end def source_path_globbed globbed_path_with_extensions(source_path.relative_path_from(root_path)) end def resolved_paths fetch(:resolved_paths) end def resolved_paths_globbed resolved_paths.map { |p| globbed_path_with_extensions(p) } end def source_entry_path source_path.join(fetch(:source_entry_path)) end def public_path root_path.join(fetch(:public_root_path)) end def public_output_path public_path.join(fetch(:public_output_path)) end def public_manifest_path public_output_path.join("manifest.json") end def cache_manifest? fetch(:cache_manifest) end def cache_path root_path.join(fetch(:cache_path)) end def extensions fetch(:extensions) end def check_yarn_integrity=(value) data[:check_yarn_integrity] = value end def check_yarn_integrity? fetch(:check_yarn_integrity) end def webpack_compile_output? fetch(:webpack_compile_output) end def extract_css? fetch(:extract_css) end private def fetch(key) data.fetch(key, defaults[key]) end def data @data ||= load end def load YAML.load(config_path.read)[env].deep_symbolize_keys rescue Errno::ENOENT => e raise "Webpacker configuration file not found #{config_path}. " \ "Please run rails webpacker:install " \ "Error: #{e.message}" rescue Psych::SyntaxError => e raise "YAML syntax error occurred while parsing #{config_path}. " \ "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ "Error: #{e.message}" end def defaults @defaults ||= \ HashWithIndifferentAccess.new(YAML.load_file(File.expand_path("../../install/config/webpacker.yml", __FILE__))[env]) end def globbed_path_with_extensions(path) "#{path}/**/*{#{extensions.join(',')}}" end end webpacker-4.2.2/lib/webpacker/webpack_runner.rb0000644000175000017500000000123513712041056020551 0ustar pravipravirequire "shellwords" require "webpacker/runner" module Webpacker class WebpackRunner < Webpacker::Runner def run env = Webpacker::Compiler.env cmd = if node_modules_bin_exist? ["#{@node_modules_bin_path}/webpack"] else ["yarn", "webpack"] end if ARGV.include?("--debug") cmd = [ "node", "--inspect-brk"] + cmd ARGV.delete("--debug") end cmd += ["--config", @webpack_config] + @argv Dir.chdir(@app_path) do Kernel.exec env, *cmd end end private def node_modules_bin_exist? File.exist?("#{@node_modules_bin_path}/webpack") end end end webpacker-4.2.2/lib/webpacker/dev_server_runner.rb0000644000175000017500000000356113712041056021305 0ustar pravipravirequire "shellwords" require "socket" require "webpacker/configuration" require "webpacker/dev_server" require "webpacker/runner" module Webpacker class DevServerRunner < Webpacker::Runner def run load_config detect_port! execute_cmd end private def load_config app_root = Pathname.new(@app_path) config = Configuration.new( root_path: app_root, config_path: app_root.join("config/webpacker.yml"), env: ENV["RAILS_ENV"] ) dev_server = DevServer.new(config) @hostname = dev_server.host @port = dev_server.port @pretty = dev_server.pretty? rescue Errno::ENOENT, NoMethodError $stdout.puts "webpack dev_server configuration not found in #{config.config_path}[#{ENV["RAILS_ENV"]}]." $stdout.puts "Please run bundle exec rails webpacker:install to install Webpacker" exit! end def detect_port! server = TCPServer.new(@hostname, @port) server.close rescue Errno::EADDRINUSE $stdout.puts "Another program is running on port #{@port}. Set a new port in #{@config_file} for dev_server" exit! end def execute_cmd env = Webpacker::Compiler.env cmd = if node_modules_bin_exist? ["#{@node_modules_bin_path}/webpack-dev-server"] else ["yarn", "webpack-dev-server"] end if ARGV.include?("--debug") cmd = [ "node", "--inspect-brk"] + cmd ARGV.delete("--debug") end cmd += ["--config", @webpack_config] cmd += ["--progress", "--color"] if @pretty Dir.chdir(@app_path) do Kernel.exec env, *cmd end end def node_modules_bin_exist? File.exist?("#{@node_modules_bin_path}/webpack-dev-server") end end end webpacker-4.2.2/lib/webpacker/instance.rb0000644000175000017500000000145313712041056017352 0ustar pravipraviclass Webpacker::Instance cattr_accessor(:logger) { ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) } attr_reader :root_path, :config_path def initialize(root_path: Rails.root, config_path: Rails.root.join("config/webpacker.yml")) @root_path, @config_path = root_path, config_path end def env @env ||= Webpacker::Env.inquire self end def config @config ||= Webpacker::Configuration.new( root_path: root_path, config_path: config_path, env: env ) end def compiler @compiler ||= Webpacker::Compiler.new self end def dev_server @dev_server ||= Webpacker::DevServer.new config end def manifest @manifest ||= Webpacker::Manifest.new self end def commands @commands ||= Webpacker::Commands.new self end end webpacker-4.2.2/lib/webpacker/runner.rb0000644000175000017500000000130013712041056017046 0ustar pravipravimodule Webpacker class Runner def self.run(argv) $stdout.sync = true new(argv).run end def initialize(argv) @argv = argv @app_path = File.expand_path(".", Dir.pwd) @node_modules_bin_path = ENV["WEBPACKER_NODE_MODULES_BIN_PATH"] || `yarn bin`.chomp @webpack_config = File.join(@app_path, "config/webpack/#{ENV["NODE_ENV"]}.js") unless File.exist?(@webpack_config) $stderr.puts "webpack config #{@webpack_config} not found, please run 'bundle exec rails webpacker:install' to install Webpacker with default configs or add the missing config file for your custom environment." exit! end end end end webpacker-4.2.2/lib/webpacker/manifest.rb0000644000175000017500000000706613712041056017362 0ustar pravipravi# Singleton registry for accessing the packs path using a generated manifest. # This allows javascript_pack_tag, stylesheet_pack_tag, asset_pack_path to take a reference to, # say, "calendar.js" or "calendar.css" and turn it into "/packs/calendar-1016838bab065ae1e314.js" or # "/packs/calendar-1016838bab065ae1e314.css". # # When the configuration is set to on-demand compilation, with the `compile: true` option in # the webpacker.yml file, any lookups will be preceded by a compilation if one is needed. class Webpacker::Manifest class MissingEntryError < StandardError; end delegate :config, :compiler, :dev_server, to: :@webpacker def initialize(webpacker) @webpacker = webpacker end def refresh @data = load end def lookup_pack_with_chunks(name, pack_type = {}) compile if compiling? manifest_pack_type = manifest_type(pack_type[:type]) manifest_pack_name = manifest_name(name, manifest_pack_type) find("entrypoints")[manifest_pack_name][manifest_pack_type] rescue NoMethodError nil end def lookup_pack_with_chunks!(name, pack_type = {}) lookup_pack_with_chunks(name, pack_type) || handle_missing_entry(name) end # Computes the relative path for a given Webpacker asset using manifest.json. # If no asset is found, returns nil. # # Example: # # Webpacker.manifest.lookup('calendar.js') # => "/packs/calendar-1016838bab065ae1e122.js" def lookup(name, pack_type = {}) compile if compiling? find(full_pack_name(name, pack_type[:type])) end # Like lookup, except that if no asset is found, raises a Webpacker::Manifest::MissingEntryError. def lookup!(name, pack_type = {}) lookup(name, pack_type) || handle_missing_entry(name) end private def compiling? config.compile? && !dev_server.running? end def compile Webpacker.logger.tagged("Webpacker") { compiler.compile } end def data if config.cache_manifest? @data ||= load else refresh end end def find(name) data[name.to_s].presence end def full_pack_name(name, pack_type) return name unless File.extname(name.to_s).empty? "#{name}.#{manifest_type(pack_type)}" end def handle_missing_entry(name) raise Webpacker::Manifest::MissingEntryError, missing_file_from_manifest_error(name) end def load if config.public_manifest_path.exist? JSON.parse config.public_manifest_path.read else {} end end # The `manifest_name` method strips of the file extension of the name, because in the # manifest hash the entrypoints are defined by their pack name without the extension. # When the user provides a name with a file extension, we want to try to strip it off. def manifest_name(name, pack_type) return name if File.extname(name.to_s).empty? File.basename(name, pack_type) end def manifest_type(pack_type) case pack_type when :javascript then "js" when :stylesheet then "css" else pack_type.to_s end end def missing_file_from_manifest_error(bundle_name) <<-MSG Webpacker can't find #{bundle_name} in #{config.public_manifest_path}. Possible causes: 1. You want to set webpacker.yml value of compile to true for your environment unless you are using the `webpack -w` or the webpack-dev-server. 2. webpack has not yet re-run to reflect updates. 3. You have misconfigured Webpacker's config/webpacker.yml file. 4. Your webpack configuration is not creating a manifest. Your manifest contains: #{JSON.pretty_generate(@data)} MSG end end webpacker-4.2.2/lib/webpacker/env.rb0000644000175000017500000000175013712041056016336 0ustar pravipraviclass Webpacker::Env DEFAULT = "production".freeze delegate :config_path, :logger, to: :@webpacker def self.inquire(webpacker) new(webpacker).inquire end def initialize(webpacker) @webpacker = webpacker end def inquire fallback_env_warning if config_path.exist? && !current current || DEFAULT.inquiry end private def current Rails.env.presence_in(available_environments) end def fallback_env_warning logger.info "RAILS_ENV=#{Rails.env} environment is not defined in config/webpacker.yml, falling back to #{DEFAULT} environment" end def available_environments if config_path.exist? YAML.load(config_path.read).keys else [].freeze end rescue Psych::SyntaxError => e raise "YAML syntax error occurred while parsing #{config_path}. " \ "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ "Error: #{e.message}" end end webpacker-4.2.2/lib/webpacker/helper.rb0000644000175000017500000002031513712041056017023 0ustar pravipravimodule Webpacker::Helper # Returns the current Webpacker instance. # Could be overridden to use multiple Webpacker # configurations within the same app (e.g. with engines). def current_webpacker_instance Webpacker.instance end # Computes the relative path for a given Webpacker asset. # Returns the relative path using manifest.json and passes it to asset_path helper. # This will use asset_path internally, so most of their behaviors will be the same. # # Example: # # # When extract_css is false in webpacker.yml and the file is a css: # <%= asset_pack_path 'calendar.css' %> # => nil # # # When extract_css is true in webpacker.yml or the file is not a css: # <%= asset_pack_path 'calendar.css' %> # => "/packs/calendar-1016838bab065ae1e122.css" def asset_pack_path(name, **options) if current_webpacker_instance.config.extract_css? || !stylesheet?(name) asset_path(current_webpacker_instance.manifest.lookup!(name), options) end end # Computes the absolute path for a given Webpacker asset. # Returns the absolute path using manifest.json and passes it to asset_url helper. # This will use asset_url internally, so most of their behaviors will be the same. # # Example: # # # When extract_css is false in webpacker.yml and the file is a css: # <%= asset_pack_url 'calendar.css' %> # => nil # # # When extract_css is true in webpacker.yml or the file is not a css: # <%= asset_pack_url 'calendar.css' %> # => "http://example.com/packs/calendar-1016838bab065ae1e122.css" def asset_pack_url(name, **options) if current_webpacker_instance.config.extract_css? || !stylesheet?(name) asset_url(current_webpacker_instance.manifest.lookup!(name), options) end end # Creates an image tag that references the named pack file. # # Example: # # <%= image_pack_tag 'application.png', size: '16x10', alt: 'Edit Entry' %> # Edit Entry def image_pack_tag(name, **options) image_tag(resolve_path_to_image(name), options) end # Creates a link tag for a favicon that references the named pack file. # # Example: # # <%= favicon_pack_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png' %> # def favicon_pack_tag(name, **options) favicon_link_tag(resolve_path_to_image(name), options) end # Creates a script tag that references the named pack file, as compiled by webpack per the entries list # in config/webpack/shared.js. By default, this list is auto-generated to match everything in # app/javascript/packs/*.js. In production mode, the digested reference is automatically looked up. # # Example: # # <%= javascript_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # => # def javascript_pack_tag(*names, **options) javascript_include_tag(*sources_from_manifest_entries(names, type: :javascript), **options) end # Creates script tags that reference the js chunks from entrypoints when using split chunks API, # as compiled by webpack per the entries list in config/webpack/shared.js. # By default, this list is auto-generated to match everything in # app/javascript/packs/*.js and all the dependent chunks. In production mode, the digested reference is automatically looked up. # See: https://webpack.js.org/plugins/split-chunks-plugin/ # Example: # # <%= javascript_packs_with_chunks_tag 'calendar', 'map', 'data-turbolinks-track': 'reload' %> # => # # # # # # DO: # <%= javascript_packs_with_chunks_tag 'calendar', 'map' %> # DON'T: # <%= javascript_packs_with_chunks_tag 'calendar' %> # <%= javascript_packs_with_chunks_tag 'map' %> def javascript_packs_with_chunks_tag(*names, **options) javascript_include_tag(*sources_from_manifest_entrypoints(names, type: :javascript), **options) end # Creates a link tag, for preloading, that references a given Webpacker asset. # In production mode, the digested reference is automatically looked up. # See: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content # Example: # # <%= preload_pack_asset 'fonts/fa-regular-400.woff2' %> # => # def preload_pack_asset(name, **options) if self.class.method_defined?(:preload_link_tag) preload_link_tag(current_webpacker_instance.manifest.lookup!(name), options) else raise "You need Rails >= 5.2 to use this tag." end end # Creates a link tag that references the named pack file, as compiled by webpack per the entries list # in config/webpack/shared.js. By default, this list is auto-generated to match everything in # app/javascript/packs/*.js. In production mode, the digested reference is automatically looked up. # # Note: If the development server is running and hot module replacement is active, this will return nothing. # In that setup you need to configure your styles to be inlined in your JavaScript for hot reloading. # # Examples: # # # When extract_css is false in webpacker.yml: # <%= stylesheet_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # => # nil # # # When extract_css is true in webpacker.yml: # <%= stylesheet_pack_tag 'calendar', 'data-turbolinks-track': 'reload' %> # => # def stylesheet_pack_tag(*names, **options) if current_webpacker_instance.config.extract_css? stylesheet_link_tag(*sources_from_manifest_entries(names, type: :stylesheet), **options) end end # Creates link tags that reference the css chunks from entrypoints when using split chunks API, # as compiled by webpack per the entries list in config/webpack/shared.js. # By default, this list is auto-generated to match everything in # app/javascript/packs/*.js and all the dependent chunks. In production mode, the digested reference is automatically looked up. # See: https://webpack.js.org/plugins/split-chunks-plugin/ # # Examples: # # <%= stylesheet_packs_with_chunks_tag 'calendar', 'map' %> # => # # # # DO: # <%= stylesheet_packs_with_chunks_tag 'calendar', 'map' %> # DON'T: # <%= stylesheet_packs_with_chunks_tag 'calendar' %> # <%= stylesheet_packs_with_chunks_tag 'map' %> def stylesheet_packs_with_chunks_tag(*names, **options) if current_webpacker_instance.config.extract_css? stylesheet_link_tag(*sources_from_manifest_entrypoints(names, type: :stylesheet), **options) end end private def stylesheet?(name) File.extname(name) == ".css" end def sources_from_manifest_entries(names, type:) names.map { |name| current_webpacker_instance.manifest.lookup!(name, type: type) }.flatten end def sources_from_manifest_entrypoints(names, type:) names.map { |name| current_webpacker_instance.manifest.lookup_pack_with_chunks!(name, type: type) }.flatten.uniq end def resolve_path_to_image(name) path = name.starts_with?("media/images/") ? name : "media/images/#{name}" asset_path(current_webpacker_instance.manifest.lookup!(path)) rescue asset_path(current_webpacker_instance.manifest.lookup!(name)) end end webpacker-4.2.2/lib/webpacker/compiler.rb0000644000175000017500000000637013712041056017363 0ustar pravipravirequire "open3" require "digest/sha1" class Webpacker::Compiler # Additional paths that test compiler needs to watch # Webpacker::Compiler.watched_paths << 'bower_components' cattr_accessor(:watched_paths) { [] } # Additional environment variables that the compiler is being run with # Webpacker::Compiler.env['FRONTEND_API_KEY'] = 'your_secret_key' cattr_accessor(:env) { {} } delegate :config, :logger, to: :webpacker def initialize(webpacker) @webpacker = webpacker end def compile if stale? run_webpack.tap do |success| # We used to only record the digest on success # However, the output file is still written on error, (at least with ts-loader), meaning that the # digest should still be updated. If it's not, you can end up in a situation where a recompile doesn't # take place when it should. # See https://github.com/rails/webpacker/issues/2113 record_compilation_digest end else logger.info "Everything's up-to-date. Nothing to do" true end end # Returns true if all the compiled packs are up to date with the underlying asset files. def fresh? watched_files_digest == last_compilation_digest end # Returns true if the compiled packs are out of date with the underlying asset files. def stale? !fresh? end private attr_reader :webpacker def last_compilation_digest compilation_digest_path.read if compilation_digest_path.exist? && config.public_manifest_path.exist? rescue Errno::ENOENT, Errno::ENOTDIR end def watched_files_digest files = Dir[*default_watched_paths, *watched_paths].reject { |f| File.directory?(f) } file_ids = files.sort.map { |f| "#{File.basename(f)}/#{Digest::SHA1.file(f).hexdigest}" } Digest::SHA1.hexdigest(file_ids.join("/")) end def record_compilation_digest config.cache_path.mkpath compilation_digest_path.write(watched_files_digest) end def run_webpack logger.info "Compiling..." stdout, stderr, status = Open3.capture3( webpack_env, "#{RbConfig.ruby} ./bin/webpack", chdir: File.expand_path(config.root_path) ) if status.success? logger.info "Compiled all packs in #{config.public_output_path}" logger.error "#{stderr}" unless stderr.empty? if config.webpack_compile_output? logger.info stdout end else non_empty_streams = [stdout, stderr].delete_if(&:empty?) logger.error "Compilation failed:\n#{non_empty_streams.join("\n\n")}" end status.success? end def default_watched_paths [ *config.resolved_paths_globbed, config.source_path_globbed, "yarn.lock", "package.json", "config/webpack/**/*" ].freeze end def compilation_digest_path config.cache_path.join("last-compilation-digest-#{webpacker.env}") end def webpack_env return env unless defined?(ActionController::Base) env.merge("WEBPACKER_ASSET_HOST" => ENV.fetch("WEBPACKER_ASSET_HOST", ActionController::Base.helpers.compute_asset_host), "WEBPACKER_RELATIVE_URL_ROOT" => ENV.fetch("WEBPACKER_RELATIVE_URL_ROOT", ActionController::Base.relative_url_root)) end end webpacker-4.2.2/lib/webpacker/dev_server_proxy.rb0000644000175000017500000000170113712041056021147 0ustar pravipravirequire "rack/proxy" class Webpacker::DevServerProxy < Rack::Proxy delegate :config, :dev_server, to: :@webpacker def initialize(app = nil, opts = {}) @webpacker = opts.delete(:webpacker) || Webpacker.instance opts[:streaming] = false if Rails.env.test? && !opts.key?(:streaming) super end def perform_request(env) if env["PATH_INFO"].start_with?("/#{public_output_uri_path}") && dev_server.running? env["HTTP_HOST"] = env["HTTP_X_FORWARDED_HOST"] = env["HTTP_X_FORWARDED_SERVER"] = dev_server.host_with_port env["HTTP_X_FORWARDED_PROTO"] = env["HTTP_X_FORWARDED_SCHEME"] = dev_server.protocol unless dev_server.https? env["HTTPS"] = env["HTTP_X_FORWARDED_SSL"] = "off" end env["SCRIPT_NAME"] = "" super(env) else @app.call(env) end end private def public_output_uri_path config.public_output_path.relative_path_from(config.public_path).to_s + "/" end end webpacker-4.2.2/lib/webpacker/version.rb0000644000175000017500000000014413712041056017227 0ustar pravipravimodule Webpacker # Change the version in package.json too, please! VERSION = "4.2.2".freeze end webpacker-4.2.2/lib/webpacker/commands.rb0000644000175000017500000000234213712041056017345 0ustar pravipraviclass Webpacker::Commands delegate :config, :compiler, :manifest, :logger, to: :@webpacker def initialize(webpacker) @webpacker = webpacker end def clean(count = 2) if config.public_output_path.exist? && config.public_manifest_path.exist? && versions.count > count versions.drop(count).flat_map(&:last).each do |file| File.delete(file) if File.file?(file) logger.info "Removed #{file}" end end true end def clobber config.public_output_path.rmtree if config.public_output_path.exist? config.cache_path.rmtree if config.cache_path.exist? end def bootstrap manifest.refresh end def compile compiler.compile.tap do |success| manifest.refresh if success end end private def versions all_files = Dir.glob("#{config.public_output_path}/**/*") manifest_config = Dir.glob("#{config.public_manifest_path}*") packs = all_files - manifest_config - current_version packs.group_by { |file| File.mtime(file).utc.to_i }.sort.reverse end def current_version manifest.refresh.values.map do |value| next if value.is_a?(Hash) File.join(config.root_path, "public", value) end.compact end end webpacker-4.2.2/lib/tasks/0000755000175000017500000000000013712041056014400 5ustar pravipraviwebpacker-4.2.2/lib/tasks/webpacker.rake0000644000175000017500000000364213712041056017214 0ustar pravipravitasks = { "webpacker:info" => "Provides information on Webpacker's environment", "webpacker:install" => "Installs and setup webpack with Yarn", "webpacker:compile" => "Compiles webpack bundles based on environment", "webpacker:clean" => "Remove old compiled webpacks", "webpacker:clobber" => "Removes the webpack compiled output directory", "webpacker:check_node" => "Verifies if Node.js is installed", "webpacker:check_yarn" => "Verifies if Yarn is installed", "webpacker:check_binstubs" => "Verifies that webpack & webpack-dev-server are present", "webpacker:binstubs" => "Installs Webpacker binstubs in this application", "webpacker:verify_install" => "Verifies if Webpacker is installed", "webpacker:yarn_install" => "Support for older Rails versions. Install all JavaScript dependencies as specified via Yarn", "webpacker:install:react" => "Installs and setup example React component", "webpacker:install:vue" => "Installs and setup example Vue component", "webpacker:install:angular" => "Installs and setup example Angular component", "webpacker:install:elm" => "Installs and setup example Elm component", "webpacker:install:svelte" => "Installs and setup example Svelte component", "webpacker:install:stimulus" => "Installs and setup example Stimulus component", "webpacker:install:erb" => "Installs Erb loader with an example", "webpacker:install:coffee" => "Installs CoffeeScript loader with an example", "webpacker:install:typescript" => "Installs Typescript loader with an example" }.freeze desc "Lists all available tasks in Webpacker" task :webpacker do puts "Available Webpacker tasks are:" tasks.each { |task, message| puts task.ljust(30) + message } end webpacker-4.2.2/lib/tasks/webpacker/0000755000175000017500000000000013712041056016343 5ustar pravipraviwebpacker-4.2.2/lib/tasks/webpacker/check_binstubs.rake0000644000175000017500000000061713712041056022201 0ustar pravipravinamespace :webpacker do desc "Verifies that webpack & webpack-dev-server are present." task :check_binstubs do unless File.exist?("bin/webpack") $stderr.puts "webpack binstubs not found.\n"\ "Have you run rails webpacker:install ?\n"\ "Make sure the bin directory or binstubs are not included in .gitignore\n"\ "Exiting!" exit! end end end webpacker-4.2.2/lib/tasks/webpacker/info.rake0000644000175000017500000000127613712041056020150 0ustar pravipravirequire "webpacker/version" namespace :webpacker do desc "Provide information on Webpacker's environment" task :info do $stdout.puts "Ruby: #{`ruby --version`}" $stdout.puts "Rails: #{Rails.version}" $stdout.puts "Webpacker: #{Webpacker::VERSION}" $stdout.puts "Node: #{`node --version`}" $stdout.puts "Yarn: #{`yarn --version`}" $stdout.puts "\n" $stdout.puts "@rails/webpacker: \n#{`npm list @rails/webpacker version`}" $stdout.puts "Is bin/webpack present?: #{File.exist? 'bin/webpack'}" $stdout.puts "Is bin/webpack-dev-server present?: #{File.exist? 'bin/webpack-dev-server'}" $stdout.puts "Is bin/yarn present?: #{File.exist? 'bin/yarn'}" end end webpacker-4.2.2/lib/tasks/webpacker/check_node.rake0000644000175000017500000000164013712041056021272 0ustar pravipravinamespace :webpacker do desc "Verifies if Node.js is installed" task :check_node do begin node_version = `node -v || nodejs -v` raise Errno::ENOENT if node_version.blank? pkg_path = Pathname.new("#{__dir__}/../../../package.json").realpath node_requirement = JSON.parse(pkg_path.read)["engines"]["node"] requirement = Gem::Requirement.new(node_requirement) version = Gem::Version.new(node_version.strip.tr("v", "")) unless requirement.satisfied_by?(version) $stderr.puts "Webpacker requires Node.js #{requirement} and you are using #{version}" $stderr.puts "Please upgrade Node.js https://nodejs.org/en/download/" $stderr.puts "Exiting!" && exit! end rescue Errno::ENOENT $stderr.puts "Node.js not installed. Please download and install Node.js https://nodejs.org/en/download/" $stderr.puts "Exiting!" && exit! end end end webpacker-4.2.2/lib/tasks/webpacker/verify_install.rake0000644000175000017500000000066213712041056022245 0ustar pravipravirequire "webpacker/configuration" namespace :webpacker do desc "Verifies if Webpacker is installed" task verify_install: [:check_node, :check_yarn, :check_binstubs] do unless Webpacker.config.config_path.exist? $stderr.puts "Configuration config/webpacker.yml file not found. \n"\ "Make sure webpacker:install is run successfully before " \ "running dependent tasks" exit! end end end webpacker-4.2.2/lib/tasks/webpacker/check_yarn.rake0000644000175000017500000000162213712041056021316 0ustar pravipravinamespace :webpacker do desc "Verifies if Yarn is installed" task :check_yarn do begin yarn_version = `yarn --version` raise Errno::ENOENT if yarn_version.blank? pkg_path = Pathname.new("#{__dir__}/../../../package.json").realpath yarn_requirement = JSON.parse(pkg_path.read)["engines"]["yarn"] requirement = Gem::Requirement.new(yarn_requirement) version = Gem::Version.new(yarn_version) unless requirement.satisfied_by?(version) $stderr.puts "Webpacker requires Yarn #{requirement} and you are using #{version}" $stderr.puts "Please upgrade Yarn https://yarnpkg.com/lang/en/docs/install/" $stderr.puts "Exiting!" && exit! end rescue Errno::ENOENT $stderr.puts "Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/" $stderr.puts "Exiting!" && exit! end end end webpacker-4.2.2/lib/tasks/webpacker/compile.rake0000644000175000017500000000236013712041056020640 0ustar pravipravi$stdout.sync = true def yarn_install_available? rails_major = Rails::VERSION::MAJOR rails_minor = Rails::VERSION::MINOR rails_major > 5 || (rails_major == 5 && rails_minor >= 1) end def enhance_assets_precompile # yarn:install was added in Rails 5.1 deps = yarn_install_available? ? [] : ["webpacker:yarn_install"] Rake::Task["assets:precompile"].enhance(deps) do Rake::Task["webpacker:compile"].invoke end end namespace :webpacker do desc "Compile JavaScript packs using webpack for production with digests" task compile: ["webpacker:verify_install", :environment] do Webpacker.with_node_env(ENV.fetch("NODE_ENV", "production")) do Webpacker.ensure_log_goes_to_stdout do if Webpacker.compile # Successful compilation! else # Failed compilation exit! end end end end end # Compile packs after we've compiled all other assets during precompilation skip_webpacker_precompile = %w(no false n f).include?(ENV["WEBPACKER_PRECOMPILE"]) unless skip_webpacker_precompile if Rake::Task.task_defined?("assets:precompile") enhance_assets_precompile else Rake::Task.define_task("assets:precompile" => ["webpacker:yarn_install", "webpacker:compile"]) end end webpacker-4.2.2/lib/tasks/webpacker/clobber.rake0000644000175000017500000000075013712041056020621 0ustar pravipravirequire "webpacker/configuration" namespace :webpacker do desc "Remove the webpack compiled output directory" task clobber: ["webpacker:verify_install", :environment] do Webpacker.clobber $stdout.puts "Removed webpack output path directory #{Webpacker.config.public_output_path}" end end # Run clobber if the assets:clobber is run if Rake::Task.task_defined?("assets:clobber") Rake::Task["assets:clobber"].enhance do Rake::Task["webpacker:clobber"].invoke end end webpacker-4.2.2/lib/tasks/webpacker/install.rake0000644000175000017500000000076013712041056020660 0ustar pravipraviinstall_template_path = File.expand_path("../../install/template.rb", __dir__).freeze bin_path = ENV["BUNDLE_BIN"] || "./bin" namespace :webpacker do desc "Install Webpacker in this application" task install: [:check_node, :check_yarn] do if Rails::VERSION::MAJOR >= 5 exec "#{RbConfig.ruby} #{bin_path}/rails app:template LOCATION=#{install_template_path}" else exec "#{RbConfig.ruby} #{bin_path}/rake rails:template LOCATION=#{install_template_path}" end end end webpacker-4.2.2/lib/tasks/webpacker/yarn_install.rake0000644000175000017500000000100713712041056021704 0ustar pravipravinamespace :webpacker do desc "Support for older Rails versions. Install all JavaScript dependencies as specified via Yarn" task :yarn_install do system "yarn install --no-progress" exit(1) unless $?.success? end end def enhance_yarn_install Rake::Task["yarn:install"].enhance do exit(1) unless $?.success? end end if Rake::Task.task_defined?("yarn:install") enhance_yarn_install else # this is mainly for pre-5.x era Rake::Task.define_task("yarn:install" => "webpacker:yarn_install") end webpacker-4.2.2/lib/tasks/webpacker/clean.rake0000644000175000017500000000074313712041056020275 0ustar pravipravi$stdout.sync = true require "webpacker/configuration" namespace :webpacker do desc "Remove old compiled webpacks" task :clean, [:keep] => ["webpacker:verify_install", :environment] do |_, args| Webpacker.ensure_log_goes_to_stdout do Webpacker.clean(Integer(args.keep || 2)) end end end # Run clean if the assets:clean is run if Rake::Task.task_defined?("assets:clean") Rake::Task["assets:clean"].enhance do Rake::Task["webpacker:clean"].invoke end end webpacker-4.2.2/lib/tasks/webpacker/binstubs.rake0000644000175000017500000000077613712041056021052 0ustar pravipravibinstubs_template_path = File.expand_path("../../install/binstubs.rb", __dir__).freeze bin_path = ENV["BUNDLE_BIN"] || "./bin" namespace :webpacker do desc "Installs Webpacker binstubs in this application" task binstubs: [:check_node, :check_yarn] do if Rails::VERSION::MAJOR >= 5 exec "#{RbConfig.ruby} #{bin_path}/rails app:template LOCATION=#{binstubs_template_path}" else exec "#{RbConfig.ruby} #{bin_path}/rake rails:template LOCATION=#{binstubs_template_path}" end end end webpacker-4.2.2/lib/tasks/installers.rake0000644000175000017500000000212213712041056017421 0ustar pravipraviinstallers = { "Angular": :angular, "Elm": :elm, "React": :react, "Vue": :vue, "Erb": :erb, "Coffee": :coffee, "Typescript": :typescript, "Svelte": :svelte, "Stimulus": :stimulus }.freeze dependencies = { "Angular": [:typescript] } bin_path = ENV["BUNDLE_BIN"] || "./bin" namespace :webpacker do namespace :install do installers.each do |name, task_name| desc "Install everything needed for #{name}" task task_name => ["webpacker:verify_install"] do template = File.expand_path("../install/#{task_name}.rb", __dir__) base_path = if Rails::VERSION::MAJOR >= 5 "#{RbConfig.ruby} #{bin_path}/rails app:template" else "#{RbConfig.ruby} #{bin_path}/rake rails:template" end dependencies[name] ||= [] dependencies[name].each do |dependency| dependency_template = File.expand_path("../install/#{dependency}.rb", __dir__) system "#{base_path} LOCATION=#{dependency_template}" end exec "#{base_path} LOCATION=#{template}" end end end end webpacker-4.2.2/.travis.yml0000644000175000017500000000261013712041056014615 0ustar pravipravilanguage: ruby dist: xenial before_install: - gem install rubygems-update && update_rubygems # Rails 4.2 doesn't support bundler 2.0, so we need to lock bundler to # v1.17.3. This is just for Ruby 2.5 which ships with bundler 2.x on Travis # CI while Ruby 2.6 does not. # https://github.com/travis-ci/travis-rubies/issues/57#issuecomment-458981237 - yes | rvm @global do gem install bundler -v 1.17.3 || true rvm: - 2.3.8 - 2.4.6 - 2.5.5 - 2.6.3 - ruby-head gemfile: - gemfiles/Gemfile-rails.4.2.x - gemfiles/Gemfile-rails.5.0.x - gemfiles/Gemfile-rails.5.1.x - gemfiles/Gemfile-rails.5.2.x - gemfiles/Gemfile-rails.6.0.x - gemfiles/Gemfile-rails-edge cache: bundler: true directories: - node_modules yarn: true install: - bundle install --jobs 3 --retry 3 - nvm install 10 - node -v - npm i -g yarn - yarn script: - yarn lint - yarn test - bundle exec rubocop - bundle exec rake test matrix: allow_failures: - gemfile: gemfiles/Gemfile-rails-edge - rvm: ruby-head exclude: - rvm: 2.3.8 gemfile: gemfiles/Gemfile-rails-edge - rvm: 2.4.6 gemfile: gemfiles/Gemfile-rails-edge - rvm: 2.5.5 gemfile: gemfiles/Gemfile-rails-edge - rvm: ruby-head gemfile: gemfiles/Gemfile-rails.4.2.x - rvm: 2.3.8 gemfile: gemfiles/Gemfile-rails.6.0.x - rvm: 2.4.6 gemfile: gemfiles/Gemfile-rails.6.0.x webpacker-4.2.2/CONTRIBUTING.md0000644000175000017500000000126313712041056014740 0ustar pravipravi## Setting Up a Development Environment 1. Install [Yarn](https://yarnpkg.com/) 2. Run the following commands to set up the development environment. ``` bundle install yarn ``` ## Making sure your changes pass all tests There are a number of automated checks which run on Travis CI when a pull request is created. You can run those checks on your own locally to make sure that your changes would not break the CI build. ### 1. Check the code for JavaScript style violations ``` yarn lint ``` ### 2. Check the code for Ruby style violations ``` bundle exec rubocop ``` ### 3. Run the JavaScript test suite ``` yarn test ``` ### 4. Run the Ruby test suite ``` bundle exec rake test ``` webpacker-4.2.2/.rubocop.yml0000644000175000017500000000550613712041056014765 0ustar pravipravirequire: rubocop-performance AllCops: TargetRubyVersion: 2.2 # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop # to ignore them, so only the ones explicitly set in this file are enabled. DisabledByDefault: true Exclude: - 'lib/install/templates/**' - 'vendor/**/*' - 'node_modules/**/*' # Prefer &&/|| over and/or. Style/AndOr: Enabled: true # Do not use braces for hash literals when they are the last argument of a # method call. Style/BracesAroundHashParameters: Enabled: true # Align `when` with `case`. Layout/CaseIndentation: Enabled: true # Align comments with method definitions. Layout/CommentIndentation: Enabled: true # No extra empty lines. Layout/EmptyLines: Enabled: true # In a regular class definition, no empty lines around the body. Layout/EmptyLinesAroundClassBody: Enabled: true # In a regular method definition, no empty lines around the body. Layout/EmptyLinesAroundMethodBody: Enabled: true # In a regular module definition, no empty lines around the body. Layout/EmptyLinesAroundModuleBody: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. Style/HashSyntax: Enabled: true # Method definitions after `private` or `protected` isolated calls need one # extra level of indentation. Layout/IndentationConsistency: Enabled: true EnforcedStyle: rails # Two spaces, no tabs (for indentation). Layout/IndentationWidth: Enabled: true Layout/SpaceAfterColon: Enabled: true Layout/SpaceAfterComma: Enabled: true Layout/SpaceAroundEqualsInParameterDefault: Enabled: true Layout/SpaceAroundKeyword: Enabled: true Layout/SpaceAroundOperators: Enabled: true Layout/SpaceBeforeFirstArg: Enabled: true # Defining a method with parameters needs parentheses. Style/MethodDefParentheses: Enabled: true # Use `foo {}` not `foo{}`. Layout/SpaceBeforeBlockBraces: Enabled: true # Use `foo { bar }` not `foo {bar}`. Layout/SpaceInsideBlockBraces: Enabled: true # Use `{ a: 1 }` not `{a:1}`. Layout/SpaceInsideHashLiteralBraces: Enabled: true Layout/SpaceInsideParens: Enabled: true # Check quotes usage according to lint rule below. Style/StringLiterals: Enabled: true EnforcedStyle: double_quotes # Detect hard tabs, no hard tabs. Layout/Tab: Enabled: true # Blank lines should not have any spaces. Layout/TrailingBlankLines: Enabled: true # No trailing whitespace. Layout/TrailingWhitespace: Enabled: true # Use quotes for string literals when they are enough. Style/UnneededPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for # assignments, where it should be aligned with the LHS. Layout/EndAlignment: Enabled: true EnforcedStyleAlignWith: variable # Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. Lint/RequireParentheses: Enabled: true webpacker-4.2.2/MIT-LICENSE0000644000175000017500000000207313712041056014143 0ustar pravipraviCopyright (c) 2016-2019 David Heinemeier Hansson, Basecamp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. webpacker-4.2.2/Gemfile0000644000175000017500000000025113712041056013776 0ustar pravipravisource "https://rubygems.org" gemspec gem "rails" gem "rake", ">= 11.1" gem "rack-proxy", require: false group :test do gem "minitest", "~> 5.0" gem "byebug" end webpacker-4.2.2/package/0000755000175000017500000000000013712041056014100 5ustar pravipraviwebpacker-4.2.2/package/config.js0000644000175000017500000000266613712041056015715 0ustar pravipraviconst { resolve } = require('path') const { safeLoad } = require('js-yaml') const { readFileSync } = require('fs') const deepMerge = require('./utils/deep_merge') const { isArray, ensureTrailingSlash } = require('./utils/helpers') const { railsEnv } = require('./env') const defaultConfigPath = require.resolve('../lib/install/config/webpacker.yml') const configPath = resolve('config', 'webpacker.yml') const getDefaultConfig = () => { const defaultConfig = safeLoad(readFileSync(defaultConfigPath), 'utf8') return defaultConfig[railsEnv] || defaultConfig.production } const defaults = getDefaultConfig() const app = safeLoad(readFileSync(configPath), 'utf8')[railsEnv] if (isArray(app.extensions) && app.extensions.length) delete defaults.extensions if (isArray(app.static_assets_extensions) && app.static_assets_extensions.length) { delete defaults.static_assets_extensions } const config = deepMerge(defaults, app) config.outputPath = resolve(config.public_root_path, config.public_output_path) // Ensure that the publicPath includes our asset host so dynamic imports // (code-splitting chunks and static assets) load from the CDN instead of a relative path. const getPublicPath = () => { const rootUrl = ensureTrailingSlash(process.env.WEBPACKER_ASSET_HOST || '/') return `${rootUrl}${config.public_output_path}/` } config.publicPath = getPublicPath() config.publicPathWithoutCDN = `/${config.public_output_path}/` module.exports = config webpacker-4.2.2/package/index.js0000644000175000017500000000121513712041056015544 0ustar pravipravi/* eslint global-require: 0 */ /* eslint import/no-dynamic-require: 0 */ const { resolve } = require('path') const { existsSync } = require('fs') const Environment = require('./environments/base') const loaders = require('./rules') const config = require('./config') const devServer = require('./dev_server') const { nodeEnv } = require('./env') const createEnvironment = () => { const path = resolve(__dirname, 'environments', `${nodeEnv}.js`) const constructor = existsSync(path) ? require(path) : Environment return new constructor() } module.exports = { config, devServer, environment: createEnvironment(), Environment, loaders } webpacker-4.2.2/package/__tests__/0000755000175000017500000000000013712041056016036 5ustar pravipraviwebpacker-4.2.2/package/__tests__/config.js0000644000175000017500000000235713712041056017650 0ustar pravipravi/* global test expect, describe */ const { chdirCwd, chdirTestApp, resetEnv } = require('../utils/helpers') chdirTestApp() const config = require('../config') describe('Config', () => { beforeEach(() => jest.resetModules() && resetEnv()) afterAll(chdirCwd) test('public path', () => { process.env.RAILS_ENV = 'development' const config = require('../config') expect(config.publicPath).toEqual('/packs/') }) test('public path with asset host', () => { process.env.RAILS_ENV = 'development' process.env.WEBPACKER_ASSET_HOST = 'http://foo.com/' const config = require('../config') expect(config.publicPath).toEqual('http://foo.com/packs/') }) test('should return extensions as listed in app config', () => { expect(config.extensions).toEqual([ '.mjs', '.js', '.sass', '.scss', '.css', '.module.sass', '.module.scss', '.module.css', '.png', '.svg', '.gif', '.jpeg', '.jpg' ]) }) test('should return static assets extensions as listed in app config', () => { expect(config.static_assets_extensions).toEqual([ '.jpg', '.jpeg', '.png', '.gif', '.tiff', '.ico', '.svg', ]) }) }) webpacker-4.2.2/package/__tests__/staging.js0000644000175000017500000000147213712041056020034 0ustar pravipravi/* test expect, describe, afterAll, beforeEach */ const { resolve } = require('path') const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('Custom environment', () => { afterAll(chdirCwd) describe('toWebpackConfig', () => { beforeEach(() => jest.resetModules()) test('should use staging config and default production environment', () => { process.env.RAILS_ENV = 'staging' delete process.env.NODE_ENV const { environment } = require('../index') const config = environment.toWebpackConfig() expect(config.output.path).toEqual(resolve('public', 'packs-staging')) expect(config.output.publicPath).toEqual('/packs-staging/') expect(config).toMatchObject({ devtool: 'source-map', stats: 'normal' }) }) }) }) webpacker-4.2.2/package/__tests__/production.js0000644000175000017500000000145113712041056020563 0ustar pravipravi/* test expect, describe, afterAll, beforeEach */ const { resolve } = require('path') const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('Production environment', () => { afterAll(chdirCwd) describe('toWebpackConfig', () => { beforeEach(() => jest.resetModules()) test('should use production config and environment', () => { process.env.RAILS_ENV = 'production' process.env.NODE_ENV = 'production' const { environment } = require('../index') const config = environment.toWebpackConfig() expect(config.output.path).toEqual(resolve('public', 'packs')) expect(config.output.publicPath).toEqual('/packs/') expect(config).toMatchObject({ devtool: 'source-map', stats: 'normal' }) }) }) }) webpacker-4.2.2/package/__tests__/development.js0000644000175000017500000000150613712041056020720 0ustar pravipravi/* test expect, describe, afterAll, beforeEach */ const { resolve } = require('path') const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('Development environment', () => { afterAll(chdirCwd) describe('toWebpackConfig', () => { beforeEach(() => jest.resetModules()) test('should use development config and environment', () => { process.env.RAILS_ENV = 'development' process.env.NODE_ENV = 'development' const { environment } = require('../index') const config = environment.toWebpackConfig() expect(config.output.path).toEqual(resolve('public', 'packs')) expect(config.output.publicPath).toEqual('/packs/') expect(config).toMatchObject({ devServer: { host: 'localhost', port: 3035 } }) }) }) }) webpacker-4.2.2/package/__tests__/dev_server.js0000644000175000017500000000252013712041056020537 0ustar pravipravi/* global test expect, describe */ const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('DevServer', () => { beforeEach(() => jest.resetModules()) afterAll(chdirCwd) test('with NODE_ENV and RAILS_ENV set to development', () => { process.env.NODE_ENV = 'development' process.env.RAILS_ENV = 'development' process.env.WEBPACKER_DEV_SERVER_HOST = '0.0.0.0' process.env.WEBPACKER_DEV_SERVER_PORT = 5000 const devServer = require('../dev_server') expect(devServer).toBeDefined() expect(devServer.host).toEqual('0.0.0.0') expect(devServer.port).toEqual('5000') }) test('with custom env prefix', () => { const config = require('../config') config.dev_server.env_prefix = 'TEST_WEBPACKER_DEV_SERVER' process.env.NODE_ENV = 'development' process.env.RAILS_ENV = 'development' process.env.TEST_WEBPACKER_DEV_SERVER_HOST = '0.0.0.0' process.env.TEST_WEBPACKER_DEV_SERVER_PORT = 5000 const devServer = require('../dev_server') expect(devServer).toBeDefined() expect(devServer.host).toEqual('0.0.0.0') expect(devServer.port).toEqual('5000') }) test('with NODE_ENV and RAILS_ENV set to production', () => { process.env.RAILS_ENV = 'production' process.env.NODE_ENV = 'production' expect(require('../dev_server')).toEqual({}) }) }) webpacker-4.2.2/package/__tests__/test.js0000644000175000017500000000136313712041056017356 0ustar pravipravi/* test expect, describe, afterAll, beforeEach */ const { resolve } = require('path') const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('Test environment', () => { afterAll(chdirCwd) describe('toWebpackConfig', () => { beforeEach(() => jest.resetModules()) test('should use test config and production environment', () => { process.env.RAILS_ENV = 'test' process.env.NODE_ENV = 'test' const { environment } = require('../index') const config = environment.toWebpackConfig() expect(config.output.path).toEqual(resolve('public', 'packs-test')) expect(config.output.publicPath).toEqual('/packs-test/') expect(config.devServer).toEqual(undefined) }) }) }) webpacker-4.2.2/package/__tests__/env.js0000644000175000017500000000224713712041056017171 0ustar pravipravi/* global test expect, describe */ const { chdirTestApp, chdirCwd } = require('../utils/helpers') chdirTestApp() describe('Env', () => { beforeEach(() => jest.resetModules()) afterAll(chdirCwd) test('with NODE_ENV and RAILS_ENV set to development', () => { process.env.RAILS_ENV = 'development' process.env.NODE_ENV = 'development' expect(require('../env')).toEqual({ railsEnv: 'development', nodeEnv: 'development' }) }) test('with undefined NODE_ENV and RAILS_ENV set to development', () => { process.env.RAILS_ENV = 'development' delete process.env.NODE_ENV expect(require('../env')).toEqual({ railsEnv: 'development', nodeEnv: 'production' }) }) test('with undefined NODE_ENV and RAILS_ENV', () => { delete process.env.NODE_ENV delete process.env.RAILS_ENV expect(require('../env')).toEqual({ railsEnv: 'production', nodeEnv: 'production' }) }) test('with a non-standard environment', () => { process.env.RAILS_ENV = 'staging' process.env.NODE_ENV = 'staging' expect(require('../env')).toEqual({ railsEnv: 'staging', nodeEnv: 'production' }) }) }) webpacker-4.2.2/package/rules/0000755000175000017500000000000013712041056015232 5ustar pravipraviwebpacker-4.2.2/package/rules/file.js0000644000175000017500000000101213712041056016501 0ustar pravipraviconst { join } = require('path') const { source_path: sourcePath, static_assets_extensions: fileExtensions } = require('../config') module.exports = { test: new RegExp(`(${fileExtensions.join('|')})$`, 'i'), use: [ { loader: 'file-loader', options: { name(file) { if (file.includes(sourcePath)) { return 'media/[path][name]-[hash].[ext]' } return 'media/[folder]/[name]-[hash:8].[ext]' }, context: join(sourcePath) } } ] } webpacker-4.2.2/package/rules/index.js0000644000175000017500000000077713712041056016712 0ustar pravipraviconst babel = require('./babel') const file = require('./file') const css = require('./css') const sass = require('./sass') const moduleCss = require('./module.css') const moduleSass = require('./module.sass') const nodeModules = require('./node_modules') // Webpack loaders are processed in reverse order // https://webpack.js.org/concepts/loaders/#loader-features // Lastly, process static files using file loader module.exports = { file, css, sass, moduleCss, moduleSass, nodeModules, babel } webpacker-4.2.2/package/rules/sass.js0000644000175000017500000000030213712041056016534 0ustar pravipraviconst getStyleRule = require('../utils/get_style_rule') module.exports = getStyleRule(/\.(scss|sass)(\.erb)?$/i, false, [ { loader: 'sass-loader', options: { sourceMap: true } } ]) webpacker-4.2.2/package/rules/css.js0000644000175000017500000000014413712041056016357 0ustar pravipraviconst getStyleRule = require('../utils/get_style_rule') module.exports = getStyleRule(/\.(css)$/i) webpacker-4.2.2/package/rules/babel.js0000644000175000017500000000126713712041056016643 0ustar pravipraviconst { join, resolve } = require('path') const { cache_path: cachePath, source_path: sourcePath, resolved_paths: resolvedPaths } = require('../config') const { nodeEnv } = require('../env') // Process application Javascript code with Babel. // Uses application .babelrc to apply any transformations module.exports = { test: /\.(js|jsx|mjs)?(\.erb)?$/, include: [sourcePath, ...resolvedPaths].map((p) => resolve(p)), exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { cacheDirectory: join(cachePath, 'babel-loader-node-modules'), cacheCompression: nodeEnv === 'production', compact: nodeEnv === 'production' } } ] } webpacker-4.2.2/package/rules/module.sass.js0000644000175000017500000000027113712041056020025 0ustar pravipraviconst getStyleRule = require('../utils/get_style_rule') module.exports = getStyleRule(/\.(scss|sass)$/i, true, [ { loader: 'sass-loader', options: { sourceMap: true } } ]) webpacker-4.2.2/package/rules/module.css.js0000644000175000017500000000015213712041056017642 0ustar pravipraviconst getStyleRule = require('../utils/get_style_rule') module.exports = getStyleRule(/\.(css)$/i, true) webpacker-4.2.2/package/rules/node_modules.js0000644000175000017500000000147313712041056020252 0ustar pravipraviconst { join } = require('path') const { cache_path: cachePath } = require('../config') const { nodeEnv } = require('../env') // Compile standard ES features for JS in node_modules with Babel. // Regex details for exclude: https://regex101.com/r/SKPnnv/1 module.exports = { test: /\.(js|mjs)$/, include: /node_modules/, exclude: /(?:@?babel(?:\/|\\{1,2}|-).+)|regenerator-runtime|core-js|^webpack$|^webpack-assets-manifest$|^webpack-cli$|^webpack-sources$|^@rails\/webpacker$/, use: [ { loader: 'babel-loader', options: { babelrc: false, presets: [['@babel/preset-env', { modules: false }]], cacheDirectory: join(cachePath, 'babel-loader-node-modules'), cacheCompression: nodeEnv === 'production', compact: false, sourceMaps: false } } ] } webpacker-4.2.2/package/environments/0000755000175000017500000000000013712041056016627 5ustar pravipraviwebpacker-4.2.2/package/environments/base.js0000644000175000017500000001066513712041056020107 0ustar pravipravi/* eslint global-require: 0 */ /* eslint import/no-dynamic-require: 0 */ const { basename, dirname, join, relative, resolve } = require('path') const { sync } = require('glob') const extname = require('path-complete-extname') const webpack = require('webpack') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const WebpackAssetsManifest = require('webpack-assets-manifest') const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin') const PnpWebpackPlugin = require('pnp-webpack-plugin') const { isNotObject, prettyPrint } = require('../utils/helpers') const deepMerge = require('../utils/deep_merge') const { ConfigList, ConfigObject } = require('../config_types') const rules = require('../rules') const config = require('../config') const getLoaderList = () => { const result = new ConfigList() Object.keys(rules).forEach((key) => result.append(key, rules[key])) return result } const getPluginList = () => { const result = new ConfigList() result.append( 'Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))) ) result.append('CaseSensitivePaths', new CaseSensitivePathsPlugin()) result.append( 'MiniCssExtract', new MiniCssExtractPlugin({ filename: 'css/[name]-[contenthash:8].css', chunkFilename: 'css/[name]-[contenthash:8].chunk.css' }) ) result.append( 'Manifest', new WebpackAssetsManifest({ integrity: false, entrypoints: true, writeToDisk: true, publicPath: config.publicPathWithoutCDN }) ) return result } const getExtensionsGlob = () => { const { extensions } = config return extensions.length === 1 ? `**/*${extensions[0]}` : `**/*{${extensions.join(',')}}` } const getEntryObject = () => { const result = new ConfigObject() const glob = getExtensionsGlob() const rootPath = join(config.source_path, config.source_entry_path) const paths = sync(join(rootPath, glob)) paths.forEach((path) => { const namespace = relative(join(rootPath), dirname(path)) const name = join(namespace, basename(path, extname(path))) result.set(name, resolve(path)) }) return result } const getModulePaths = () => { const result = new ConfigList() result.append('source', resolve(config.source_path)) if (config.resolved_paths) { config.resolved_paths.forEach((path) => result.append(path, resolve(path))) } result.append('node_modules', 'node_modules') return result } const getBaseConfig = () => new ConfigObject({ mode: 'production', output: { filename: 'js/[name]-[contenthash].js', chunkFilename: 'js/[name]-[contenthash].chunk.js', hotUpdateChunkFilename: 'js/[id]-[hash].hot-update.js', path: config.outputPath, publicPath: config.publicPath }, resolve: { extensions: config.extensions, plugins: [PnpWebpackPlugin] }, resolveLoader: { modules: ['node_modules'], plugins: [PnpWebpackPlugin.moduleLoader(module)] }, node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty' } }) module.exports = class Base { constructor() { this.loaders = getLoaderList() this.plugins = getPluginList() this.config = getBaseConfig() this.entry = getEntryObject() this.resolvedModules = getModulePaths() } splitChunks(callback = null) { let appConfig = {} const defaultConfig = { optimization: { // Split vendor and common chunks // https://twitter.com/wSokra/status/969633336732905474 splitChunks: { chunks: 'all', name: false }, // Separate runtime chunk to enable long term caching // https://twitter.com/wSokra/status/969679223278505985 runtimeChunk: true } } if (callback) { appConfig = callback(defaultConfig) if (isNotObject(appConfig)) { throw new Error(` ${prettyPrint(appConfig)} is not a valid splitChunks configuration. See https://webpack.js.org/plugins/split-chunks-plugin/#configuration `) } } return this.config.merge(deepMerge(defaultConfig, appConfig)) } toWebpackConfig() { return this.config.merge({ entry: this.entry.toObject(), module: { strictExportPresence: true, rules: [{ parser: { requireEnsure: false } }, ...this.loaders.values()] }, plugins: this.plugins.values(), resolve: { modules: this.resolvedModules.values() } }) } } webpacker-4.2.2/package/environments/__tests__/0000755000175000017500000000000013712041056020565 5ustar pravipraviwebpacker-4.2.2/package/environments/__tests__/base.js0000644000175000017500000000436213712041056022042 0ustar pravipravi/* global test expect, describe, afterAll, beforeEach */ // environment.js expects to find config/webpacker.yml and resolved modules from // the root of a Rails project const { chdirTestApp, chdirCwd } = require('../../utils/helpers') chdirTestApp() const { resolve } = require('path') const rules = require('../../rules') const { ConfigList } = require('../../config_types') const Environment = require('../base') describe('Environment', () => { afterAll(chdirCwd) let environment describe('toWebpackConfig', () => { beforeEach(() => { environment = new Environment() }) test('should return entry', () => { const config = environment.toWebpackConfig() expect(config.entry.application).toEqual( resolve('app', 'javascript', 'packs', 'application.js') ) }) test('should return output', () => { const config = environment.toWebpackConfig() expect(config.output.filename).toEqual('js/[name]-[contenthash].js') expect(config.output.chunkFilename).toEqual('js/[name]-[contenthash].chunk.js') }) test('should return default loader rules for each file in config/loaders', () => { const config = environment.toWebpackConfig() const defaultRules = Object.keys(rules) const configRules = config.module.rules expect(defaultRules.length).toEqual(7) expect(configRules.length).toEqual(8) }) test('should return default plugins', () => { const config = environment.toWebpackConfig() expect(config.plugins.length).toEqual(4) }) test('should return default resolveLoader', () => { const config = environment.toWebpackConfig() expect(config.resolveLoader.modules).toEqual(['node_modules']) }) test('should return default resolve.modules with additions', () => { const config = environment.toWebpackConfig() expect(config.resolve.modules).toEqual([ resolve('app', 'javascript'), resolve('app/assets'), resolve('/etc/yarn'), 'node_modules' ]) }) test('returns plugins property as Array', () => { const config = environment.toWebpackConfig() expect(config.plugins).toBeInstanceOf(Array) expect(config.plugins).not.toBeInstanceOf(ConfigList) }) }) }) webpacker-4.2.2/package/environments/production.js0000644000175000017500000000371013712041056021354 0ustar pravipraviconst TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const safePostCssParser = require('postcss-safe-parser') const Base = require('./base') module.exports = class extends Base { constructor() { super() this.plugins.append( 'Compression', new CompressionPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', cache: true, test: /\.(js|css|html|json|ico|svg|eot|otf|ttf|map)$/ }) ) if ('brotli' in process.versions) { this.plugins.append( 'Compression Brotli', new CompressionPlugin({ filename: '[path].br[query]', algorithm: 'brotliCompress', cache: true, test: /\.(js|css|html|json|ico|svg|eot|otf|ttf|map)$/ }) ) } this.plugins.append( 'OptimizeCSSAssets', new OptimizeCSSAssetsPlugin({ parser: safePostCssParser, map: { inline: false, annotation: true } }) ) this.config.merge({ devtool: 'source-map', stats: 'normal', bail: true, optimization: { minimizer: [ new TerserPlugin({ parallel: true, cache: true, sourceMap: true, terserOptions: { parse: { // Let terser parse ecma 8 code but always output // ES5 compliant code for older browsers ecma: 8 }, compress: { ecma: 5, warnings: false, comparisons: false }, mangle: { safari10: true }, output: { ecma: 5, comments: false, ascii_only: true } } }) ] } }) } } webpacker-4.2.2/package/environments/development.js0000644000175000017500000000255713712041056021520 0ustar pravipraviconst webpack = require('webpack') const Base = require('./base') const devServer = require('../dev_server') const { outputPath: contentBase, publicPath } = require('../config') module.exports = class extends Base { constructor() { super() if (devServer.hmr) { this.plugins.append('HotModuleReplacement', new webpack.HotModuleReplacementPlugin()) this.config.output.filename = '[name]-[hash].js' } this.config.merge({ mode: 'development', cache: true, devtool: 'cheap-module-source-map', output: { pathinfo: true }, devServer: { clientLogLevel: 'none', compress: devServer.compress, quiet: devServer.quiet, disableHostCheck: devServer.disable_host_check, host: devServer.host, port: devServer.port, https: devServer.https, hot: devServer.hmr, contentBase, inline: devServer.inline, useLocalIp: devServer.use_local_ip, public: devServer.public, publicPath, historyApiFallback: { disableDotRule: true }, headers: devServer.headers, overlay: devServer.overlay, stats: { entrypoints: false, errorDetails: true, modules: false, moduleTrace: false }, watchOptions: devServer.watch_options } }) } } webpacker-4.2.2/package/environments/test.js0000644000175000017500000000010713712041056020142 0ustar pravipraviconst Base = require('./base') module.exports = class extends Base {} webpacker-4.2.2/package/utils/0000755000175000017500000000000013712041056015240 5ustar pravipraviwebpacker-4.2.2/package/utils/get_style_rule.js0000644000175000017500000000201613712041056020623 0ustar pravipraviconst MiniCssExtractPlugin = require('mini-css-extract-plugin') const { resolve } = require('path') const config = require('../config') const styleLoader = { loader: 'style-loader' } const getStyleRule = (test, modules = false, preprocessors = []) => { const use = [ { loader: 'css-loader', options: { sourceMap: true, importLoaders: 2, modules: modules ? { localIdentName: '[name]__[local]___[hash:base64:5]' } : false } }, { loader: 'postcss-loader', options: { config: { path: resolve() }, sourceMap: true } }, ...preprocessors ] const options = modules ? { include: /\.module\.[a-z]+$/ } : { exclude: /\.module\.[a-z]+$/ } if (config.extract_css) { use.unshift(MiniCssExtractPlugin.loader) } else { use.unshift(styleLoader) } // sideEffects - See https://github.com/webpack/webpack/issues/6571 return { test, use, sideEffects: !modules, ...options } } module.exports = getStyleRule webpacker-4.2.2/package/utils/__tests__/0000755000175000017500000000000013712041056017176 5ustar pravipraviwebpacker-4.2.2/package/utils/__tests__/get_style_rule.js0000644000175000017500000000364413712041056022571 0ustar pravipraviconst { chdirTestApp, chdirCwd } = require('../helpers') chdirTestApp() const getStyleRule = require('../get_style_rule') describe('getStyleRule', () => { afterAll(chdirCwd) test('excludes modules by default', () => { const cssRule = getStyleRule(/\.(css)$/i) const expectation = { test: /\.(css)$/i, exclude: /\.module\.[a-z]+$/ } expect(cssRule).toMatchObject(expectation) }) test('includes modules if set to true', () => { const cssRule = getStyleRule(/\.(scss)$/i, true) const expectation = { test: /\.(scss)$/i, include: /\.module\.[a-z]+$/ } expect(cssRule).toMatchObject(expectation) }) test('adds extra preprocessors if supplied', () => { const expectation = [{ foo: 'bar' }] const cssRule = getStyleRule(/\.(css)$/i, true, expectation) expect(cssRule.use).toMatchObject(expect.arrayContaining(expectation)) }) test('adds mini-css-extract-plugin when extract_css is true', () => { const MiniCssExtractPlugin = require('mini-css-extract-plugin') const expectation = [MiniCssExtractPlugin.loader] require('../../config').extract_css = true const cssRule = getStyleRule(/\.(css)$/i) expect(cssRule.use).toMatchObject(expect.arrayContaining(expectation)) }) test('adds style-loader when extract_css is true', () => { const expectation = [{loader: 'style-loader'}] require('../../config').extract_css = false const cssRule = getStyleRule(/\.(css)$/i) expect(cssRule.use).toMatchObject(expect.objectContaining(expectation)) }) test(`doesn't add mini-css-extract-plugin when extract_css is false`, () => { const MiniCssExtractPlugin = require('mini-css-extract-plugin') const expectation = [MiniCssExtractPlugin.loader] require('../../config').extract_css = false const cssRule = getStyleRule(/\.(css)$/i) expect(cssRule.use).toMatchObject(expect.not.arrayContaining(expectation)) }) }) webpacker-4.2.2/package/utils/__tests__/deep_merge.js0000644000175000017500000000056313712041056021634 0ustar pravipravi/* global test expect */ const deepMerge = require('../deep_merge') test('deep merge objects together', () => { const object1 = { foo: { bar: [1, 2, 3], z: 1 }, x: 0 } const object2 = { foo: { bar: ['x', 'y'] }, x: 1, y: 2 } const expectation = { foo: { bar: [1, 2, 3, 'x', 'y'], z: 1 }, x: 1, y: 2 } expect(deepMerge(object1, object2)).toEqual(expectation) }) webpacker-4.2.2/package/utils/__tests__/deep_assign.js0000644000175000017500000000176313712041056022024 0ustar pravipravi/* global test expect */ const deepAssign = require('../deep_assign') describe('deepAssign()', () => { test('deeply assigns nested properties', () => { const object = { foo: { bar: { } } } const path = 'foo.bar' const value = { x: 1, y: 2 } const expectation = { foo: { bar: { x: 1, y: 2 } } } expect(deepAssign(object, path, value)).toEqual(expectation) }) test('allows assignment of a literal false', () => { const object = { foo: { bar: { } } } const path = 'foo.bar' const value = false const expectation = { foo: { bar: false } } expect(deepAssign(object, path, value)).toEqual(expectation) }) test('does not allow assignment of other falsy values', () => { const object = { foo: { bar: { } } } const path = 'foo.bar' const values = [undefined, null, 0, ''] values.forEach(value => { const expectation = new Error(`Value can't be ${value}`) expect(() => deepAssign(object, path, value)).toThrow(expectation) }) }) }) webpacker-4.2.2/package/utils/__tests__/objectify.js0000644000175000017500000000042613712041056021514 0ustar pravipravi/* global test expect */ const objectify = require('../objectify') test('Get object from a string path', () => { const object = { foo: { bar: { x: 1 } } } expect(objectify('foo.bar', object)).toEqual({ x: 1 }) expect(objectify('some.bar', object)).toEqual(undefined) }) webpacker-4.2.2/package/utils/deep_merge.js0000644000175000017500000000111113712041056017664 0ustar pravipraviconst { isObject, isArray, isEqual, isEmpty } = require('./helpers') const deepMerge = (target, source) => { if (isEmpty(target)) return source if (isEmpty(source)) return target if (isEqual(target, source)) return source if (isArray(target) && isArray(source)) return [...new Set([...target, ...source])] if (!(isObject(target) && isObject(source))) return source return [...Object.keys(target), ...Object.keys(source)].reduce( (result, key) => ({ ...result, [key]: deepMerge(target[key], source[key]) }), {} ) } module.exports = deepMerge webpacker-4.2.2/package/utils/deep_assign.js0000644000175000017500000000122013712041056020052 0ustar pravipraviconst { canMerge, prettyPrint } = require('./helpers') const deepMerge = require('./deep_merge') const deepAssign = (obj, path, value) => { if (!value && value !== false) throw new Error(`Value can't be ${value}`) const keys = path.split('.') const key = keys.pop() const objRef = keys.reduce((acc, currentValue) => { /* eslint no-param-reassign: 0 */ if (!acc[currentValue]) acc[currentValue] = {} return acc[currentValue] }, obj) if (!objRef) throw new Error(`Prop not found: ${path} in ${prettyPrint(obj)}`) objRef[key] = canMerge(value) ? deepMerge(objRef[key], value) : value return obj } module.exports = deepAssign webpacker-4.2.2/package/utils/helpers.js0000644000175000017500000000243413712041056017243 0ustar pravipraviconst { stringify } = require('flatted/cjs') const isObject = (value) => typeof value === 'object' && value !== null && (value.length === undefined || value.length === null) const isNotObject = (value) => !isObject(value) const isBoolean = (str) => /^true/.test(str) || /^false/.test(str) const isEmpty = (value) => value === null || value === undefined const isString = (key) => key && typeof key === 'string' const isStrPath = (key) => { if (!isString(key)) throw new Error(`Key ${key} should be string`) return isString(key) && key.includes('.') } const isArray = (value) => Array.isArray(value) const isEqual = (target, source) => stringify(target) === stringify(source) const canMerge = (value) => isObject(value) || isArray(value) const prettyPrint = (obj) => JSON.stringify(obj, null, 2) const chdirTestApp = () => { try { return process.chdir('test/test_app') } catch (e) { return null } } const chdirCwd = () => process.chdir(process.cwd()) const resetEnv = () => { process.env = {} } const ensureTrailingSlash = (path) => (path.endsWith('/') ? path : `${path}/`) module.exports = { chdirTestApp, chdirCwd, ensureTrailingSlash, isObject, isNotObject, isBoolean, isArray, isEqual, isEmpty, isStrPath, canMerge, prettyPrint, resetEnv } webpacker-4.2.2/package/utils/objectify.js0000644000175000017500000000021213712041056017547 0ustar pravipraviconst objectify = (path, obj) => path.split('.').reduce((prev, curr) => (prev ? prev[curr] : undefined), obj) module.exports = objectify webpacker-4.2.2/package/dev_server.js0000644000175000017500000000111113712041056016574 0ustar pravipraviconst { isBoolean } = require('./utils/helpers') const config = require('./config') const fetch = (key) => { const value = process.env[key] return isBoolean(value) ? JSON.parse(value) : value } const devServerConfig = config.dev_server if (devServerConfig) { const envPrefix = config.dev_server.env_prefix || 'WEBPACKER_DEV_SERVER' Object.keys(devServerConfig).forEach((key) => { const envValue = fetch(`${envPrefix}_${key.toUpperCase().replace(/_/g, '')}`) if (envValue !== undefined) devServerConfig[key] = envValue }) } module.exports = devServerConfig || {} webpacker-4.2.2/package/config_types/0000755000175000017500000000000013712041056016571 5ustar pravipraviwebpacker-4.2.2/package/config_types/index.js0000644000175000017500000000021713712041056020236 0ustar pravipraviconst ConfigObject = require('./config_object') const ConfigList = require('./config_list') module.exports = { ConfigObject, ConfigList } webpacker-4.2.2/package/config_types/__tests__/0000755000175000017500000000000013712041056020527 5ustar pravipraviwebpacker-4.2.2/package/config_types/__tests__/config_list.js0000644000175000017500000000606413712041056023373 0ustar pravipravi/* global test expect */ const ConfigList = require('../config_list') test('new', () => { const list = new ConfigList() expect(list).toBeInstanceOf(ConfigList) expect(list).toBeInstanceOf(Array) }) test('get', () => { const list = new ConfigList() list.append('key', 'value') expect(list.get('key')).toEqual('value') }) test('append', () => { const list = new ConfigList() list.append('key', 'value') expect(list.append('key1', 'value1')).toEqual([ { key: 'key', value: 'value' }, { key: 'key1', value: 'value1' } ]) }) test('prepend', () => { const list = new ConfigList() list.append('key', 'value') expect(list.prepend('key1', 'value1')).toEqual([ { key: 'key1', value: 'value1' }, { key: 'key', value: 'value' } ]) }) test('insert without position', () => { const list = new ConfigList() list.append('key', 'value') expect(list.insert('key1', 'value1')).toEqual([ { key: 'key', value: 'value' }, { key: 'key1', value: 'value1' } ]) expect(list.insert('key2', 'value2')).toEqual([ { key: 'key', value: 'value' }, { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' } ]) }) test('insert before an item', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.insert('key2', 'value2', { before: 'key' })).toEqual([ { key: 'key2', value: 'value2' }, { key: 'key', value: 'value' }, { key: 'key1', value: 'value1' } ]) expect(list.insert('key3', 'value3', { before: 'key2' })).toEqual([ { key: 'key3', value: 'value3' }, { key: 'key2', value: 'value2' }, { key: 'key', value: 'value' }, { key: 'key1', value: 'value1' } ]) }) test('insert after an item', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.insert('key2', 'value2', { after: 'key' })).toEqual([ { key: 'key', value: 'value' }, { key: 'key2', value: 'value2' }, { key: 'key1', value: 'value1' } ]) expect(list.insert('key3', 'value3', { after: 'key2' })).toEqual([ { key: 'key', value: 'value' }, { key: 'key2', value: 'value2' }, { key: 'key3', value: 'value3' }, { key: 'key1', value: 'value1' } ]) }) test('delete', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.delete('key')).toEqual([{ key: 'key1', value: 'value1' }]) expect(list.delete('key1')).toEqual([]) }) test('getIndex', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.getIndex('key')).toEqual(0) expect(list.getIndex('key2')).toEqual(-1) expect(() => list.getIndex('key2', true)).toThrow('Item key2 not found') }) test('values', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.values()).toEqual(['value', 'value1']) }) test('keys', () => { const list = new ConfigList() list.append('key', 'value') list.append('key1', 'value1') expect(list.keys()).toEqual(['key', 'key1']) }) webpacker-4.2.2/package/config_types/__tests__/config_object.js0000644000175000017500000000211413712041056023656 0ustar pravipravi/* global test expect */ const ConfigObject = require('../config_object') test('new', () => { const object = new ConfigObject() expect(object).toBeInstanceOf(ConfigObject) expect(object).toBeInstanceOf(Object) }) test('set', () => { const object = new ConfigObject() expect(object.set('key', 'value')).toEqual({ key: 'value' }) }) test('get', () => { const object = new ConfigObject() object.set('key', 'value') object.set('key1', 'value1') expect(object.get('key')).toEqual('value') }) test('delete', () => { const object = new ConfigObject() object.set('key', { key1: 'value' }) expect(object.delete('key.key1')).toEqual({ key: {} }) expect(object.delete('key')).toEqual({}) }) test('toObject', () => { const object = new ConfigObject() object.set('key', 'value') object.set('key1', 'value1') expect(object.toObject()).toEqual({ key: 'value', key1: 'value1' }) }) test('merge', () => { const object = new ConfigObject() object.set('foo', {}) expect(object.merge({ key: 'foo', value: 'bar' })).toEqual( { foo: {}, key: 'foo', value: 'bar' } ) }) webpacker-4.2.2/package/config_types/config_list.js0000644000175000017500000000303413712041056021427 0ustar pravipravi/** * @class * @extends { Array } */ class ConfigList extends Array { static get [Symbol.species]() { return Array } get(key) { const index = this.getIndex(key, true) return this[index].value } append(key, value) { return this.add({ key, value }) } prepend(key, value) { return this.add({ key, value }, 'prepend') } insert(key, value, pos = {}) { if (!(pos.before || pos.after)) return this.append(key, value) const currentIndex = this.getIndex(key) if (currentIndex >= 0) this.splice(currentIndex, 1) let newIndex = this.getIndex(pos.before || pos.after) if (pos.after) newIndex += 1 this.splice(newIndex, 0, { key, value }) return this } delete(key) { const index = this.getIndex(key, true) this.splice(index, 1) return this } getIndex(key, shouldThrow = false) { const index = this.findIndex((entry) => ( entry === key || entry.key === key || (entry.constructor && entry.constructor.name === key) )) if (shouldThrow && index < 0) throw new Error(`Item ${key} not found`) return index } add({ key, value }, strategy = 'append') { const index = this.getIndex(key) if (index >= 0) this.delete(key) switch (strategy) { case 'prepend': this.unshift({ key, value }) break default: this.push({ key, value }) } return this } values() { return this.map((item) => item.value) } keys() { return this.map((item) => item.key) } } module.exports = ConfigList webpacker-4.2.2/package/config_types/config_object.js0000644000175000017500000000223113712041056021720 0ustar pravipraviconst objectify = require('../utils/objectify') const deepAssign = require('../utils/deep_assign') const deepMerge = require('../utils/deep_merge') const { isStrPath, prettyPrint } = require('../utils/helpers') /** * @class * @extends { Object } */ class ConfigObject extends Object { constructor(props = {}) { super() this.merge(props) } get(key) { return isStrPath(key) ? objectify(key, this) : this[key] } set(key, value) { Object.assign(this, deepAssign(this, key, value)) return this } delete(key) { let obj = this let propKey = key if (isStrPath(key)) { const keys = key.split('.') propKey = keys.pop() const parentObjPath = keys.join('.') obj = objectify(parentObjPath, this) } if (!obj) throw new Error(`Prop not found: ${key} in ${prettyPrint(obj)}`) delete obj[propKey] return this } toObject() { const object = {} /* eslint no-return-assign: 0 */ Object.keys(this).forEach((key) => (object[key] = this[key])) return object } merge(config) { Object.assign(this, deepMerge(this, config)) return this } } module.exports = ConfigObject webpacker-4.2.2/package/env.js0000644000175000017500000000126113712041056015226 0ustar pravipraviconst { resolve } = require('path') const { safeLoad } = require('js-yaml') const { readFileSync } = require('fs') const NODE_ENVIRONMENTS = ['development', 'production', 'test'] const DEFAULT = 'production' const configPath = resolve('config', 'webpacker.yml') const railsEnv = process.env.RAILS_ENV const nodeEnv = process.env.NODE_ENV const config = safeLoad(readFileSync(configPath), 'utf8') const availableEnvironments = Object.keys(config).join('|') const regex = new RegExp(`^(${availableEnvironments})$`, 'g') module.exports = { railsEnv: railsEnv && railsEnv.match(regex) ? railsEnv : DEFAULT, nodeEnv: nodeEnv && NODE_ENVIRONMENTS.includes(nodeEnv) ? nodeEnv : DEFAULT } webpacker-4.2.2/.eslintrc.js0000644000175000017500000000045713712041056014752 0ustar pravipravimodule.exports = { 'extends': 'airbnb', 'rules': { 'comma-dangle': ['error', 'never'], 'import/no-unresolved': 'off', 'import/no-extraneous-dependencies': 'off', 'import/extensions': 'off', semi: ['error', 'never'], }, 'env': { 'browser': true, 'node': true, }, }; webpacker-4.2.2/.eslintignore0000644000175000017500000000006013712041056015204 0ustar pravipravilib/* node_modules/* vendor/* **/__tests__/**/* webpacker-4.2.2/README.md0000644000175000017500000005407213712041056013774 0ustar pravipravi# Webpacker [![Build Status](https://travis-ci.org/rails/webpacker.svg?branch=master)](https://travis-ci.org/rails/webpacker) [![node.js](https://img.shields.io/badge/node-%3E%3D%208.16.0-brightgreen.svg)](https://nodejs.org/en/) [![Gem](https://img.shields.io/gem/v/webpacker.svg)](https://github.com/rails/webpacker) Webpacker makes it easy to use the JavaScript pre-processor and bundler [webpack 4.x.x+](https://webpack.js.org/) to manage application-like JavaScript in Rails. It coexists with the asset pipeline, as the primary purpose for webpack is app-like JavaScript, not images, CSS, or even JavaScript Sprinkles (that all continues to live in app/assets). However, it is possible to use Webpacker for CSS, images and fonts assets as well, in which case you may not even need the asset pipeline. This is mostly relevant when exclusively using component-based JavaScript frameworks. **NOTE:** The master branch now hosts the code for v4.x.x. Please refer to [3-x-stable](https://github.com/rails/webpacker/tree/3-x-stable) branch for 3.x documentation. See the [v4-upgrade guide](docs/v4-upgrade.md) for an overview of the changes. ## Table of Contents - [Prerequisites](#prerequisites) - [Features](#features) - [Installation](#installation) - [Usage](#usage) - [Development](#development) - [Webpack Configuration](#webpack-configuration) - [Custom Rails environments](#custom-rails-environments) - [Upgrading](#upgrading) - [Yarn Integrity](#yarn-integrity) - [Integrations](#integrations) - [React](#react) - [Angular with TypeScript](#angular-with-typescript) - [Vue](#vue) - [Elm](#elm) - [Stimulus](#stimulus) - [Svelte](#svelte) - [CoffeeScript](#coffeescript) - [Erb](#erb) - [Paths](#paths) - [Resolved](#resolved) - [Watched](#watched) - [Deployment](#deployment) - [Docs](#docs) - [Contributing](#contributing) - [License](#license) ## Prerequisites * Ruby 2.2+ * Rails 4.2+ * Node.js 8.16.0+ * Yarn 1.x+ ## Features * [webpack 4.x.x](https://webpack.js.org/) * ES6 with [babel](https://babeljs.io/) * Automatic code splitting using multiple entry points * Stylesheets - Sass and CSS * Images and fonts * PostCSS - Auto-Prefixer * Asset compression, source-maps, and minification * CDN support * React, Angular, Elm and Vue support out-of-the-box * Rails view helpers * Extensible and configurable ## Installation You can either add Webpacker during setup of a new Rails 5.1+ application using new `--webpack` option: ```bash # Available Rails 5.1+ rails new myapp --webpack ``` Or add it to your `Gemfile`: ```ruby # Gemfile gem 'webpacker', '~> 4.x' # OR if you prefer to use master gem 'webpacker', git: 'https://github.com/rails/webpacker.git' yarn add https://github.com/rails/webpacker.git yarn add core-js regenerator-runtime ``` Finally, run the following to install Webpacker: ```bash bundle bundle exec rails webpacker:install # OR (on rails version < 5.0) bundle exec rake webpacker:install ``` Optional: To fix ["unmet peer dependency" warnings](https://github.com/rails/webpacker/issues/1078), ```bash yarn upgrade ``` ### Usage Once installed, you can start writing modern ES6-flavored JavaScript apps right away: ```yml app/javascript: ├── packs: │ # only webpack entry files here │ └── application.js └── src: │ └── application.css └── images: └── logo.svg ``` In `/packs/application.js`, include this at the top of the file: ```js import "core-js/stable"; import "regenerator-runtime/runtime"; ``` You 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`: ```erb <%= javascript_pack_tag 'application' %> <%= stylesheet_pack_tag 'application' %> ``` If you want to link a static asset for `` or `` tag, you can use the `asset_pack_path` helper: ```erb ``` If you are using new webpack 4 split chunks API, then consider using `javascript_packs_with_chunks_tag` helper, which creates html tags for a pack and all the dependent chunks. ```erb <%= javascript_packs_with_chunks_tag 'calendar', 'map', 'data-turbolinks-track': 'reload' %> ``` **Important:** Pass all your pack names when using `javascript_packs_with_chunks_tag` helper otherwise you will get duplicated chunks on the page. ```erb <%# DO %> <%= javascript_packs_with_chunks_tag 'calendar', 'map' %> <%# DON'T %> <%= javascript_packs_with_chunks_tag 'calendar' %> <%= javascript_packs_with_chunks_tag 'map' %> ``` **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. ### Development Webpacker ships with two binstubs: `./bin/webpack` and `./bin/webpack-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. In development, Webpacker compiles on demand rather than upfront by default. This happens when you refer to any of the pack assets using the Webpacker helper methods. This means that you don't have to run any separate processes. Compilation errors are logged to the standard Rails log. If 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/webpack-dev-server` or `ruby ./bin/webpack-dev-server`. Windows users will need to run these commands in a terminal separate from `bundle exec rails s`. This process will watch for changes in the `app/javascript/packs/*.js` files and automatically reload the browser to match. ```bash # webpack dev server ./bin/webpack-dev-server # watcher ./bin/webpack --watch --colors --progress # standalone build ./bin/webpack ``` Once you start this development server, Webpacker will automatically start proxying all webpack asset requests to this server. When you stop the server, it'll revert back to on-demand compilation. You can use environment variables as options supported by [webpack-dev-server](https://webpack.js.org/configuration/dev-server/) in the form `WEBPACKER_DEV_SERVER_