How to setup Webpack config

It has gained exceptional boost since the release of ES6 modules specification - standardized way of providing modularity to your JS code. While not being rapidly adopted by the browsers, they quickly gained popularity among developers, replacing other inferior systems, such as AMD and CommonJS. With better modularity also came greater demand for bundlers. Webpack, due to its great functionality and extendability, quickly gained the upper hand. But with the number of plugins, extensions, loaders etc. at your disposal, it’s not easy to provide one proper solution or more specific configuration for all users with different needs. That’s why Webpack configuration can be a little bit hard and exhausting for some to be dealt with. And that’s why this tutorial even exists. Here I’ll try to introduce you to the basics of creating your Webpack config. I really advise you to read this from top to bottom because there’s a prize waiting at the end. 😂 Without further ado, let’s first take a look at Webpack itself.

Webpack & company

Webpack is advertised as a static module bundler for modern JavaScript applications. It’s a popular tool for bundling web apps. With support for ES6 modules, CommonJS, AMD and @imports it can pretty much handle all resources used by everyday web apps. It has a wide community behind it with a really vast ecosystem of plugins and loaders for many different assets. With that being said, it’s not the only right tool for the work. There are plenty more high-quality bundlers out there. One of which being Rollup.js. It’s just another bundler, but a bit more tailored towards bundling libraries and other JS tools rather than web apps. There’s also a new player in the field called Parcel.js. It can be a perfect solution for everybody who doesn’t like configuration and stuff. Parcel.js provides true out-of-the-box support for many different assets and formats. These 3 are my favorites and while there’s definitely more other and based-on tools out there, I won’t be naturally listing them all. 🙃 Now, that you know of possible alternatives, here’s how to configure your Webpack step by step.

Config

To be more specific, let’s define what exactly our config should do. The following configuration should fulfill every demand of our project. In this case, it’ll be a simple SPA and PWA based on React and written in TypeScript. We’ll also use SCSS (with no support for CSS whatsoever) for a better experience while defining our styles. Let’s begin! 😁

Take a look at a skeleton of Webpack config file.

const path = require('path');

module.exports = {
  entry: './src/index.tsx',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
      extensions: []
  },
  module: {
      rules: []
  },
  plugins: []
}

So here you have it. The basic structure of our config. It’s located in the webpack.config.js file which utilizes CommonJS syntax to export our config object. Inside it, we have the entry field relatively pointing to the file where the bundler should start its work from. Then we have the output object with the proper path and filename for the generated bundle. The name uses [name] placeholder to indicate that the name of the output should correspond to the name of our module (main by default). Resolve.extensions section is basically an array of file extensions that Webpack should read and process. Next, we have module.rules which is arguably one of the most important places in the whole config. It is here where we define our loaders that should process specific files. At the end comes the plugins field where all Webpack plugins will find their place. Now, let’s populate it with some content, shall we?

// ...
    resolve: {
        extensions: [ '.tsx', '.ts', '.js', '.jsx' ]
    },
    module: {
        rules: [{
            test: /\.tsx?$/,
            use: ['babel-loader', 'ts-loader'],
            exclude: /node_modules/
        }]
    },
// ...

And… that’s mostly all that’s required to process TypeScript! Let’s take a closer look at what’s going on. In extensions, we’ve added all possible extensions we’re going to use in the future. In the rules, we provided our first rule. Its an object with 3 properties. The test is a regexp that matches all files that end with .ts or .tsx extensions and processes them with ts-loaderand then babel-loader provided in the use field. Using two processors gives us the ability to process code outputted from the TS compiler using Babel. Remember that loaders are used from the last to the first provided in the array. Finally, we exclude node_modules from matching, because who would possibly need to process these and lag his system? 😂 It’s worth mentioning that you don’t need to require ts-loader in any way, just to install it. And while we’re talking about installing, I might have forgotten to mention anything about Webpack installation, so let’s fix all that with one simple command:

npm install --save-dev webpack webpack-cli typescript @babel/core babel-loader ts-loader

Now let’s add support for SCSS!

// ...
{
    test: /\.scss$/,
    use: [
        'style-loader',
        { loader: 'css-loader', options: { importLoaders: 1 } },
        'sass-loader',
    ],
},
// ...

Here, we need to use as much as 3 loaders, so let’s install them first and don’t forget about node-sass for processing SCSS!

npm install --save-dev node-sass style-loader css-loader sass-loader

Generally what we’re doing right here is processing SCSS files using sass-loader with the node-sass lib, transform all @imports and URLs with css-loader and actually use/insert our styles with style-loader. The importLoaders option for css-loader is indicating how many loaders are used before the CSS one. In our example, it’s just one - sass-loader. Take a look at the syntax for providing loader with additional options.

Lastly, let’s get fancy and add support for bundling images aka static files!

npm install --save-dev file-loader
// ...
{
    test: /\.(jpe?g|png|gif|svg)$/i,
    loader: 'file-loader'
},
// ...

With the file-loader, Webpack processes every matching import into proper URLs. Notice, that loader field can be used instead of use when defining single loader.

Also, don’t forget about other config files, such as tsconfig.json for TypeScript

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "lib": ["es5", "es6", "dom"]
    },
    "include": [
        "./src/**/*"
    ],
}

…and .babelrc for Babel:

npm install --save-dev @babel/preset-env @babel/preset-react @babel/preset-typescript
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "env": {
    "development": {
      "presets": ["@babel/preset-typescript"]
    }
  }
}

I won’t cover these as they’re a bit out-of-topic, check out links to their pages if you want to know more - all of the tools listed in this article have awesome docs. 📙⚡

Let’s get onto plugins now.

npm install --save-dev clean-webpack-plugin html-webpack-plugin
workbox-webpack-plugin webpack-pwa-manifest
const CleanPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');
// ...
plugins: [
    new CleanPlugin(["dist"]),
    new HtmlWebpackPlugin({
        filename: 'index.html',
        title: 'Webpack Config',
        template: './src/index.html'
    }),
    new WebpackPwaManifest({
        name: 'Webpack Config',
        short_name: 'WpConfig',
        description: 'Example Webpack Config',
        background_color: '#ffffff'
    }),
    new WorkboxPlugin.GenerateSW({
        swDest: 'sw.js',
        clientsClaim: true,
        skipWaiting: true,
    })
],
// ...

In the snippet above we’re greeted with as much as 4 plugins! Each of them has its own specific purposes. Clean-webpack-plugin is responsible for cleaning output directory - a simple task. Html-webpack-plugin setups our HTML file using provided data and template file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta 
          name="viewport" 
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        >
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
</body>

</html>

That’s our template file BTW with the title taken straight from the plugin’s config object. Finally, workbox-webpack-plugin and webpack-pwa-manifest provide PWA functionalities for offline service-workers and app manifest respectively. Some of these have a lot of customization options, so go to their project pages to learn more if you plan to use them.

Production

At this point, we can safely say that our config is quite operational. But it’s not enough. With Webpack you can have multiple configs for different use-cases. The most popular example is to have 2 configs for production and development as each environment has its own specific requirements. Let’s break our webpack.config.js into 3 pieces.

Webpack.common.js will contain configuration that is the same for both development and production configs.

const CleanPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');
const path = require("path");

module.exports = {
  entry: "./src/index.tsx",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].js"
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js", ".jsx"]
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader",
          { loader: "css-loader", options: { importLoaders: 1 } },
          "sass-loader"
        ]
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loader: "file-loader"
      }
    ]
  },
  plugins: [
    new CleanPlugin(["dist"]),
    new HtmlWebpackPlugin({
        filename: 'index.html',
        title: 'Webpack Config',
        template: './src/index.html',
    }),
    new WebpackPwaManifest({
        name: 'Webpack Config',
        short_name: 'WpConfig',
        description: 'Example Webpack Config',
        background_color: '#ffffff'
    }),
    new WorkboxPlugin.GenerateSW({
        swDest: 'sw.js',
        clientsClaim: true,
        skipWaiting: true,
    })
  ]
};

Now, let’s create our webpack.prod.js config. We’ll need to merge it with our common config. To do this we can utilize webpack-merge - a tool for doing just that. So let’s install it and 2 other plugins we’ll later use.

npm install --save-dev webpack-merge uglifyjs-webpack-plugin hard-source-webpack-plugin
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [{
            test: /\.tsx?$/,
            use: ["babel-loader", "ts-loader"],
            exclude: /node_modules/
        }]
    },
    optimization: {
        minimizer: [new UglifyJsPlugin({
            sourceMap: true
        })],
    },
});

Here we can see two new properties - mode and devtool. Mode indicates our current environment - its either “production”“development” or “none”. This allows some tools to apply optimizations proper for chosen env. Devtool property refers to the way of generating source maps. Webpack has many options built-in for this property. There are also many plugins that provide additional functionalities. But “source-map” option that produces source maps from content files, is enough for us right now. Then we have our old-fashioned .ts files loader. It’s followed by new, self-explaining fields in our config. The optimization.minimizer allows us to specify a plugin used to minimize our files, which is naturally useful when targeting production. Here I’ll use uglifyjs-webpack-plugin which is well battle-tested and has good performance with solid output. Don’t forget about sourceMap option for this plugin, without that your source maps won’t be generated! Now, let’s go over to the development config file - webpack.dev.js.

const merge = require('webpack-merge');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval-source-map',
    module: {
        rules: [{
            test: /\.tsx?$/,
            loader: "babel-loader",
            exclude: /node_modules/
        }]
    },
    plugins: [
        new HardSourceWebpackPlugin()
    ]
});

At development, we only care about speed. No optimizations need to be done at that point. We only want for our code to be bundled fast. The same applies to source mapping which this time uses much faster, but the not-so-optimized “eval-source-map” option. Then, when defining our loader for TypeScript, we use only one, single loader - babel-loader. By doing this we only transpile our .ts files without type-checking them, which has a huge impact on bundling speed. That’s why earlier I defined the @babel/preset-typescript to be used on the development stage in the .babelrc file. Lastly, we have the hard-source-webpack-plugin which provides an easy way for caching our files, so our second bundling will be even faster!

And… that’s it! We have our proper environment-specific configs ready to be used!

Hot reload 🔥

So we’ve got nice configs, but who needs a fast development config without hot reloading!? That’s right - it’s getting hot!🔥 So, let’s put aside our production config for now and let’s implement this wonderful feature, shall we? Using webpack-dev-server it’s really simple! You can install it with:

npm install --save-dev webpack-dev-server

For configuration add devServer config object to our webpack.dev.js file.

// ...
devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000
}
// ...

Here we provide basic options like port, directory to serve and if compression should be done. And that’s it! To finish it let’s add two scriptsto our package.json for easier development.

"scripts": {
    "start": "webpack-dev-server --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
}

By using –config option we provide the location of our env-specific Webpack config.

So here you have it! Your very own Webpack config with support for TS/TSX, SCSS, optimize production and development settings and HMR! As a side-note, our HMR works just fine, but when it comes to React-specific stuff, there’s room for improvement. For example, if you would like to preserve your components’ states across reloads. For this, you can use react-hot-loader and follow this awesome guide while using the config you’ve already created here.

A gift 🎁

So, as you can see by following this tutorial, creating Webpack config isn’t difficult. It’s just a bit time-consuming process that can require some googling from time to time. But it can also be fun for some. But if you’re in the other group I have something special for you. I’ve created a simple CLI tool for creating basic boilerplate for your Webpack config. By using this you won’t have to spend time setting the same things up yourself over and over again. It’s called webpack-suit-up and you can download it from NPM. So, yeah, check it out if you’re interested.

I hope this tutorial helped you with the process of configuring your Webpack. For more info on Webpack, you can check out its official website. But, just as I said on the beginning, there are many other great tools that may not even require configuration. There are even those which are based on Webpack and automatically configures it. Also, even Webpack itself from v4 doesn’t require configuration, but it’s really necessary in most cases. Maybe you would like to see a complete list of interesting web bundlers out there? Or rather a guide on configuring Rollup.js? Write in the comments below. Share this article, so that others can discover it quicker. Also, follow me on Twitter or on my Facebook Page for more up-to-date content.

By :  Areknawo

#webpack #javascript

What is GEEK

Buddha Community

Asset Sync: Synchronises Assets Between Rails and S3

Asset Sync

Synchronises Assets between Rails and S3.

Asset Sync is built to run with the new Rails Asset Pipeline feature introduced in Rails 3.1. After you run bundle exec rake assets:precompile your assets will be synchronised to your S3 bucket, optionally deleting unused files and only uploading the files it needs to.

This was initially built and is intended to work on Heroku but can work on any platform.

Upgrading?

Upgraded from 1.x? Read UPGRADING.md

Installation

Since 2.x, Asset Sync depends on gem fog-core instead of fog.
This is due to fog is including many unused storage provider gems as its dependencies.

Asset Sync has no idea about what provider will be used,
so you are responsible for bundling the right gem for the provider to be used.

In your Gemfile:

gem "asset_sync"
gem "fog-aws"

Or, to use Azure Blob storage, configure as this.

gem "asset_sync"
gem "gitlab-fog-azure-rm"

# This gem seems unmaintianed
# gem "fog-azure-rm"

To use Backblaze B2, insert these.

gem "asset_sync"
gem "fog-backblaze"

Extended Installation (Faster sync with turbosprockets)

It's possible to improve asset:precompile time if you are using Rails 3.2.x the main source of which being compilation of non-digest assets.

turbo-sprockets-rails3 solves this by only compiling digest assets. Thus cutting compile time in half.

NOTE: It will be deprecated in Rails 4 as sprockets-rails has been extracted out of Rails and will only compile digest assets by default.

Configuration

Rails

Configure config/environments/production.rb to use Amazon S3 as the asset host and ensure precompiling is enabled.

  #config/environments/production.rb
  config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"

Or, to use Google Storage Cloud, configure as this.

  #config/environments/production.rb
  config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}.storage.googleapis.com"

Or, to use Azure Blob storage, configure as this.

  #config/environments/production.rb
  config.action_controller.asset_host = "//#{ENV['AZURE_STORAGE_ACCOUNT_NAME']}.blob.core.windows.net/#{ENV['FOG_DIRECTORY']}"

Or, to use Backblaze B2, configure as this.

  #config/environments/production.rb
  config.action_controller.asset_host = "//f000.backblazeb2.com/file/#{ENV['FOG_DIRECTORY']}"

On HTTPS: the exclusion of any protocol in the asset host declaration above will allow browsers to choose the transport mechanism on the fly. So if your application is available under both HTTP and HTTPS the assets will be served to match.

The only caveat with this is that your S3 bucket name must not contain any periods so, mydomain.com.s3.amazonaws.com for example would not work under HTTPS as SSL certificates from Amazon would interpret our bucket name as not a subdomain of s3.amazonaws.com, but a multi level subdomain. To avoid this don't use a period in your subdomain or switch to the other style of S3 URL.

  config.action_controller.asset_host = "//s3.amazonaws.com/#{ENV['FOG_DIRECTORY']}"

Or, to use Google Storage Cloud, configure as this.

  config.action_controller.asset_host = "//storage.googleapis.com/#{ENV['FOG_DIRECTORY']}"

Or, to use Azure Blob storage, configure as this.

  #config/environments/production.rb
  config.action_controller.asset_host = "//#{ENV['AZURE_STORAGE_ACCOUNT_NAME']}.blob.core.windows.net/#{ENV['FOG_DIRECTORY']}"

On non default S3 bucket region: If your bucket is set to a region that is not the default US Standard (us-east-1) you must use the first style of url //#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com or amazon will return a 301 permanently moved when assets are requested. Note the caveat above about bucket names and periods.

If you wish to have your assets sync to a sub-folder of your bucket instead of into the root add the following to your production.rb file

  # store assets in a 'folder' instead of bucket root
  config.assets.prefix = "/production/assets"

Also, ensure the following are defined (in production.rb or application.rb)

  • config.assets.digest is set to true.
  • config.assets.enabled is set to true.

Additionally, if you depend on any configuration that is setup in your initializers you will need to ensure that

  • config.assets.initialize_on_precompile is set to true

AssetSync

AssetSync supports the following methods of configuration.

Using the Built-in Initializer is the default method and is supposed to be used with environment variables. It's the recommended approach for deployments on Heroku.

If you need more control over configuration you will want to use a custom rails initializer.

Configuration using a YAML file (a common strategy for Capistrano deployments) is also supported.

The recommend way to configure asset_sync is by using environment variables however it's up to you, it will work fine if you hard code them too. The main reason why using environment variables is recommended is so your access keys are not checked into version control.

Built-in Initializer (Environment Variables)

The Built-in Initializer will configure AssetSync based on the contents of your environment variables.

Add your configuration details to heroku

heroku config:add AWS_ACCESS_KEY_ID=xxxx
heroku config:add AWS_SECRET_ACCESS_KEY=xxxx
heroku config:add FOG_DIRECTORY=xxxx
heroku config:add FOG_PROVIDER=AWS
# and optionally:
heroku config:add FOG_REGION=eu-west-1
heroku config:add ASSET_SYNC_GZIP_COMPRESSION=true
heroku config:add ASSET_SYNC_MANIFEST=true
heroku config:add ASSET_SYNC_EXISTING_REMOTE_FILES=keep

Or add to a traditional unix system

export AWS_ACCESS_KEY_ID=xxxx
export AWS_SECRET_ACCESS_KEY=xxxx
export FOG_DIRECTORY=xxxx

Rackspace configuration is also supported

heroku config:add RACKSPACE_USERNAME=xxxx
heroku config:add RACKSPACE_API_KEY=xxxx
heroku config:add FOG_DIRECTORY=xxxx
heroku config:add FOG_PROVIDER=Rackspace

Google Storage Cloud configuration is supported as well. The preferred option is using the GCS JSON API which requires that you create an appropriate service account, generate the signatures and make them accessible to asset sync at the prescribed location

heroku config:add FOG_PROVIDER=Google
heroku config:add GOOGLE_PROJECT=xxxx
heroku config:add GOOGLE_JSON_KEY_LOCATION=xxxx
heroku config:add FOG_DIRECTORY=xxxx

If using the S3 API the following config is required

heroku config:add FOG_PROVIDER=Google
heroku config:add GOOGLE_STORAGE_ACCESS_KEY_ID=xxxx
heroku config:add GOOGLE_STORAGE_SECRET_ACCESS_KEY=xxxx
heroku config:add FOG_DIRECTORY=xxxx

The Built-in Initializer also sets the AssetSync default for existing_remote_files to keep.

Custom Rails Initializer (config/initializers/asset_sync.rb)

If you want to enable some of the advanced configuration options you will want to create your own initializer.

Run the included Rake task to generate a starting point.

rails g asset_sync:install --provider=Rackspace
rails g asset_sync:install --provider=AWS
rails g asset_sync:install --provider=AzureRM
rails g asset_sync:install --provider=Backblaze

The generator will create a Rails initializer at config/initializers/asset_sync.rb.

AssetSync.configure do |config|
  config.fog_provider = 'AWS'
  config.fog_directory = ENV['FOG_DIRECTORY']
  config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID']
  config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
  config.aws_session_token = ENV['AWS_SESSION_TOKEN'] if ENV.key?('AWS_SESSION_TOKEN')

  # Don't delete files from the store
  # config.existing_remote_files = 'keep'
  #
  # Increase upload performance by configuring your region
  # config.fog_region = 'eu-west-1'
  #
  # Set `public` option when uploading file depending on value,
  # Setting to "default" makes asset sync skip setting the option
  # Possible values: true, false, "default" (default: true)
  # config.fog_public = true
  #
  # Change AWS signature version. Default is 4
  # config.aws_signature_version = 4
  #
  # Change canned ACL of uploaded object. Default is unset. Will override fog_public if set.
  # Choose from: private | public-read | public-read-write | aws-exec-read |
  #              authenticated-read | bucket-owner-read | bucket-owner-full-control 
  # config.aws_acl = nil 
  #
  # Change host option in fog (only if you need to)
  # config.fog_host = 's3.amazonaws.com'
  #
  # Change port option in fog (only if you need to)
  # config.fog_port = "9000"
  #
  # Use http instead of https.
  # config.fog_scheme = 'http'
  #
  # Automatically replace files with their equivalent gzip compressed version
  # config.gzip_compression = true
  #
  # Use the Rails generated 'manifest.yml' file to produce the list of files to
  # upload instead of searching the assets directory.
  # config.manifest = true
  #
  # Upload the manifest file also.
  # config.include_manifest = false
  #
  # Upload files concurrently
  # config.concurrent_uploads = false
  #
  # Number of threads when concurrent_uploads is enabled
  # config.concurrent_uploads_max_threads = 10
  #
  # Path to cache file to skip scanning remote
  # config.remote_file_list_cache_file_path = './.asset_sync_remote_file_list_cache.json'
  #
  # Fail silently.  Useful for environments such as Heroku
  # config.fail_silently = true
  #
  # Log silently. Default is `true`. But you can set it to false if more logging message are preferred.
  # Logging messages are sent to `STDOUT` when `log_silently` is falsy
  # config.log_silently = true
  #
  # Allow custom assets to be cacheable. Note: The base filename will be matched
  # If you have an asset with name `app.0b1a4cd3.js`, only `app.0b1a4cd3` will need to be matched
  # only one of `cache_asset_regexp` or `cache_asset_regexps` is allowed.
  # config.cache_asset_regexp = /\.[a-f0-9]{8}$/i
  # config.cache_asset_regexps = [ /\.[a-f0-9]{8}$/i, /\.[a-f0-9]{20}$/i ]
end

YAML (config/asset_sync.yml)

Run the included Rake task to generate a starting point.

rails g asset_sync:install --use-yml --provider=Rackspace
rails g asset_sync:install --use-yml --provider=AWS
rails g asset_sync:install --use-yml --provider=AzureRM
rails g asset_sync:install --use-yml --provider=Backblaze

The generator will create a YAML file at config/asset_sync.yml.

defaults: &defaults
  fog_provider: "AWS"
  fog_directory: "rails-app-assets"
  aws_access_key_id: "<%= ENV['AWS_ACCESS_KEY_ID'] %>"
  aws_secret_access_key: "<%= ENV['AWS_SECRET_ACCESS_KEY'] %>"

  # To use AWS reduced redundancy storage.
  # aws_reduced_redundancy: true
  #
  # You may need to specify what region your storage bucket is in
  # fog_region: "eu-west-1"
  #
  # Change AWS signature version. Default is 4
  # aws_signature_version: 4
  #
  # Change canned ACL of uploaded object. Default is unset. Will override fog_public if set.
  # Choose from: private | public-read | public-read-write | aws-exec-read |
  #              authenticated-read | bucket-owner-read | bucket-owner-full-control 
  # aws_acl: null
  #
  # Change host option in fog (only if you need to)
  # fog_host: "s3.amazonaws.com"
  #
  # Use http instead of https. Default should be "https" (at least for fog-aws)
  # fog_scheme: "http"

  existing_remote_files: keep # Existing pre-compiled assets on S3 will be kept
  # To delete existing remote files.
  # existing_remote_files: delete
  # To ignore existing remote files and overwrite.
  # existing_remote_files: ignore
  # Automatically replace files with their equivalent gzip compressed version
  # gzip_compression: true
  # Fail silently.  Useful for environments such as Heroku
  # fail_silently: true
  # Always upload. Useful if you want to overwrite specific remote assets regardless of their existence
  #  eg: Static files in public often reference non-fingerprinted application.css
  #  note: You will still need to expire them from the CDN's edge cache locations
  # always_upload: ['application.js', 'application.css', !ruby/regexp '/application-/\d{32}\.css/']
  # Ignored files. Useful if there are some files that are created dynamically on the server and you don't want to upload on deploy.
  # ignored_files: ['ignore_me.js', !ruby/regexp '/ignore_some/\d{32}\.css/']
  # Allow custom assets to be cacheable. Note: The base filename will be matched
  # If you have an asset with name "app.0b1a4cd3.js", only "app.0b1a4cd3" will need to be matched
  # cache_asset_regexps: ['cache_me.js', !ruby/regexp '/cache_some\.\d{8}\.css/']

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

Available Configuration Options

Most AssetSync configuration can be modified directly using environment variables with the Built-in initializer. e.g.

AssetSync.config.fog_provider == ENV['FOG_PROVIDER']

Simply upcase the ruby attribute names to get the equivalent environment variable to set. The only exception to that rule are the internal AssetSync config variables, they must be prepended with ASSET_SYNC_* e.g.

AssetSync.config.gzip_compression == ENV['ASSET_SYNC_GZIP_COMPRESSION']

AssetSync (optional)

  • existing_remote_files: ('keep', 'delete', 'ignore') what to do with previously precompiled files. default: 'keep'
  • gzip_compression: (true, false) when enabled, will automatically replace files that have a gzip compressed equivalent with the compressed version. default: 'false'
  • manifest: (true, false) when enabled, will use the manifest.yml generated by Rails to get the list of local files to upload. experimental. default: 'false'
  • include_manifest: (true, false) when enabled, will upload the manifest.yml generated by Rails. default: 'false'
  • concurrent_uploads: (true, false) when enabled, will upload the files in different Threads, this greatly improves the upload speed. default: 'false'
  • concurrent_uploads_max_threads: when concurrent_uploads is enabled, this determines the number of threads that will be created. default: 10
  • remote_file_list_cache_file_path: if present, use this path to cache remote file list to skip scanning remote default: nil
  • enabled: (true, false) when false, will disable asset sync. default: 'true' (enabled)
  • ignored_files: an array of files to ignore e.g. ['ignore_me.js', %r(ignore_some/\d{32}\.css)] Useful if there are some files that are created dynamically on the server and you don't want to upload on deploy default: []
  • cache_asset_regexps: an array of files to add cache headers e.g. ['cache_me.js', %r(cache_some\.\d{8}\.css)] Useful if there are some files that are added to sprockets assets list and need to be set as 'Cacheable' on uploaded server. Only rails compiled regexp is matched internally default: []

Config Method add_local_file_paths

Adding local files by providing a block:

AssetSync.configure do |config|
  # The block should return an array of file paths
  config.add_local_file_paths do
    # Any code that returns paths of local asset files to be uploaded
    # Like Webpacker
    public_root = Rails.root.join("public")
    Dir.chdir(public_root) do
      packs_dir = Webpacker.config.public_output_path.relative_path_from(public_root)
      Dir[File.join(packs_dir, '/**/**')]
    end
  end
end

The blocks are run when local files are being scanned and uploaded

Config Method file_ext_to_mime_type_overrides

It's reported that mime-types 3.x returns application/ecmascript instead of application/javascript
Such change of mime type might cause some CDN to disable asset compression
So this gem has defined a default override for file ext js to be mapped to application/javascript by default

To customize the overrides:

AssetSync.configure do |config|
  # Clear the default overrides
  config.file_ext_to_mime_type_overrides.clear

  # Add/Edit overrides
  # Will call `#to_s` for inputs
  config.file_ext_to_mime_type_overrides.add(:js, :"application/x-javascript")
end

The blocks are run when local files are being scanned and uploaded

Fog (Required)

  • fog_provider: your storage provider AWS (S3) or Rackspace (Cloud Files) or Google (Google Storage) or AzureRM (Azure Blob) or Backblaze (Backblaze B2)
  • fog_directory: your bucket name

Fog (Optional)

  • fog_region: the region your storage bucket is in e.g. eu-west-1 (AWS), ord (Rackspace), japanwest (Azure Blob)
  • fog_path_style: To use buckets with dot in names, check fog/fog#2381 (comment)

AWS

  • aws_access_key_id: your Amazon S3 access key
  • aws_secret_access_key: your Amazon S3 access secret
  • aws_acl: set canned ACL of uploaded object, will override fog_public if set

Rackspace

  • rackspace_username: your Rackspace username
  • rackspace_api_key: your Rackspace API Key.

Google Storage

When using the JSON API

  • google_project: your Google Cloud Project name where the Google Cloud Storage bucket resides
  • google_json_key_location: path to the location of the service account key. The service account key must be a JSON type key

When using the S3 API

  • google_storage_access_key_id: your Google Storage access key
  • google_storage_secret_access_key: your Google Storage access secret

Azure Blob

  • azure_storage_account_name: your Azure Blob access key
  • azure_storage_access_key: your Azure Blob access secret

Backblaze B2

  • b2_key_id: Your Backblaze B2 key ID
  • b2_key_token: Your Backblaze B2 key token
  • b2_bucket_id: Your Backblaze B2 bucket ID

Rackspace (Optional)

  • rackspace_auth_url: Rackspace auth URL, for Rackspace London use: https://lon.identity.api.rackspacecloud.com/v2.0

Amazon S3 Multiple Region Support

If you are using anything other than the US buckets with S3 then you'll want to set the region. For example with an EU bucket you could set the following environment variable.

heroku config:add FOG_REGION=eu-west-1

Or via a custom initializer

AssetSync.configure do |config|
  # ...
  config.fog_region = 'eu-west-1'
end

Or via YAML

production:  # ...  fog_region: 'eu-west-1'

Amazon (AWS) IAM Users

Amazon has switched to the more secure IAM User security policy model. When generating a user & policy for asset_sync you must ensure the policy has the following permissions, or you'll see the error:

Expected(200) <=> Actual(403 Forbidden)

IAM User Policy Example with minimum require permissions (replace bucket_name with your bucket):

{
  "Statement": [
    {
      "Action": "s3:ListBucket",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::bucket_name"
    },
    {
      "Action": "s3:PutObject*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::bucket_name/*"
    }
  ]
}

If you want to use IAM roles you must set config.aws_iam_roles = true in your initializers.

AssetSync.configure do |config|
  # ...
  config.aws_iam_roles = true
end

Automatic gzip compression

With the gzip_compression option enabled, when uploading your assets. If a file has a gzip compressed equivalent we will replace that asset with the compressed version and sets the correct headers for S3 to serve it. For example, if you have a file master.css and it was compressed to master.css.gz we will upload the .gz file to S3 in place of the uncompressed file.

If the compressed file is actually larger than the uncompressed file we will ignore this rule and upload the standard uncompressed version.

Fail Silently

With the fail_silently option enabled, when running rake assets:precompile AssetSync will never throw an error due to missing configuration variables.

With the new user_env_compile feature of Heroku (see above), this is no longer required or recommended. Yet was added for the following reasons:

With Rails 3.1 on the Heroku cedar stack, the deployment process automatically runs rake assets:precompile. If you are using ENV variable style configuration. Due to the methods with which Heroku compile slugs, there will be an error raised by asset_sync as the environment is not available. This causes heroku to install the rails31_enable_runtime_asset_compilation plugin which is not necessary when using asset_sync and also massively slows down the first incoming requests to your app.

To prevent this part of the deploy from failing (asset_sync raising a config error), but carry on as normal set fail_silently to true in your configuration and ensure to run heroku run rake assets:precompile after deploy.

Rake Task

A rake task is included within the asset_sync gem to perform the sync:

  namespace :assets do
    desc "Synchronize assets to S3"
    task :sync => :environment do
      AssetSync.sync
    end
  end

If AssetSync.config.run_on_precompile is true (default), then assets will be uploaded to S3 automatically after the assets:precompile rake task is invoked:

  if Rake::Task.task_defined?("assets:precompile:nondigest")
    Rake::Task["assets:precompile:nondigest"].enhance do
      Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile
    end
  else
    Rake::Task["assets:precompile"].enhance do
      Rake::Task["assets:sync"].invoke if defined?(AssetSync) && AssetSync.config.run_on_precompile
    end
  end

You can disable this behavior by setting AssetSync.config.run_on_precompile = false.

Sinatra/Rack Support

You can use the gem with any Rack application, but you must specify two additional options; prefix and public_path.

AssetSync.configure do |config|
  config.fog_provider = 'AWS'
  config.fog_directory = ENV['FOG_DIRECTORY']
  config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID']
  config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
  config.prefix = 'assets'
  # Can be a `Pathname` or `String`
  # Will be converted into an `Pathname`
  # If relative, will be converted into an absolute path
  # via `::Rails.root` or `::Dir.pwd`
  config.public_path = Pathname('./public')
end

Then manually call AssetSync.sync at the end of your asset precompilation task.

namespace :assets do
  desc 'Precompile assets'
  task :precompile do
    target = Pathname('./public/assets')
    manifest = Sprockets::Manifest.new(sprockets, './public/assets/manifest.json')

    sprockets.each_logical_path do |logical_path|
      if (!File.extname(logical_path).in?(['.js', '.css']) || logical_path =~ /application\.(css|js)$/) && asset = sprockets.find_asset(logical_path)
        filename = target.join(logical_path)
        FileUtils.mkpath(filename.dirname)
        puts "Write asset: #{filename}"
        asset.write_to(filename)
        manifest.compile(logical_path)
      end
    end

    AssetSync.sync
  end
end

Webpacker (> 2.0) support

  1. Add webpacker files and disable run_on_precompile:
AssetSync.configure do |config|
  # Disable automatic run on precompile in order to attach to webpacker rake task
  config.run_on_precompile = false
  # The block should return an array of file paths
  config.add_local_file_paths do
    # Support webpacker assets
    public_root = Rails.root.join("public")
    Dir.chdir(public_root) do
      packs_dir = Webpacker.config.public_output_path.relative_path_from(public_root)
      Dir[File.join(packs_dir, '/**/**')]
    end
  end
end
  1. Add a asset_sync.rake in your lib/tasks directory that enhances the correct task, otherwise asset_sync runs before webpacker:compile does:
if defined?(AssetSync)
  Rake::Task['webpacker:compile'].enhance do
    Rake::Task["assets:sync"].invoke
  end
end

Caveat

By adding local files outside the normal Rails assets directory, the uploading part works, however checking that the asset was previously uploaded is not working because asset_sync is only fetching the files in the assets directory on the remote bucket. This will mean additional time used to upload the same assets again on every precompilation.

Running the specs

Make sure you have a .env file with these details:-

# for AWS provider
AWS_ACCESS_KEY_ID=<yourkeyid>
AWS_SECRET_ACCESS_KEY=<yoursecretkey>
FOG_DIRECTORY=<yourbucket>
FOG_REGION=<youbucketregion>

# for AzureRM provider
AZURE_STORAGE_ACCOUNT_NAME=<youraccountname>
AZURE_STORAGE_ACCESS_KEY=<youraccesskey>
FOG_DIRECTORY=<yourcontainer>
FOG_REGION=<yourcontainerregion>

Make sure the bucket has read/write permissions. Then to run the tests:-

foreman run rake

Todo

  1. Add some before and after filters for deleting and uploading
  2. Support more cloud storage providers
  3. Better test coverage
  4. Add rake tasks to clean old assets from a bucket

Credits

Inspired by:

License

MIT License. Copyright 2011-2013 Rumble Labs Ltd. rumblelabs.com


Author: AssetSync
Source code: https://github.com/AssetSync/asset_sync
License:

#ruby   #ruby-on-rails 

Dexter  Goodwin

Dexter Goodwin

1650394920

Webpack: A Bundler for Javascript and Friends

webpack

Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

Install

Install with npm:

npm install --save-dev webpack

Install with yarn:

yarn add webpack --dev

Introduction

Webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

TL;DR

  • Bundles ES Modules, CommonJS, and AMD modules (even combined).
  • Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time).
  • Dependencies are resolved during compilation, reducing the runtime size.
  • Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc.
  • Highly modular plugin system to do whatever else your application requires.

Get Started

Check out webpack's quick Get Started guide and the other guides.

Browser Compatibility

Webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). Webpack also needs Promise for import() and require.ensure(). If you want to support older browsers, you will need to load a polyfill before using these expressions.

Concepts

Plugins

Webpack has a rich plugin interface. Most of the features within webpack itself use this plugin interface. This makes webpack very flexible.

NameStatusInstall SizeDescription
[mini-css-extract-plugin][mini-css]![mini-css-npm]![mini-css-size]Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.
[compression-webpack-plugin][compression]![compression-npm]![compression-size]Prepares compressed versions of assets to serve them with Content-Encoding
[html-webpack-plugin][html-plugin]![html-plugin-npm]![html-plugin-size]Simplifies creation of HTML files (index.html) to serve your bundles

Loaders

Webpack enables the use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node.js.

Loaders are activated by using loadername! prefixes in require() statements, or are automatically applied via regex from your webpack configuration.

Files

NameStatusInstall SizeDescription
[val-loader][val]![val-npm]![val-size]Executes code as module and considers exports as JS code

JSON

NameStatusInstall SizeDescription
![cson-npm]![cson-size]Loads and transpiles a CSON file

Transpiling

NameStatusInstall SizeDescription
![babel-npm]![babel-size]Loads ES2015+ code and transpiles to ES5 using Babel
![type-npm]![type-size]Loads TypeScript like JavaScript
![coffee-npm]![coffee-size]Loads CoffeeScript like JavaScript

Templating

NameStatusInstall SizeDescription
![html-npm]![html-size]Exports HTML as string, requires references to static resources
![pug-npm]![pug-size]Loads Pug templates and returns a function
![md-npm]![md-size]Compiles Markdown to HTML
![posthtml-npm]![posthtml-size]Loads and transforms a HTML file using PostHTML
![hbs-npm]![hbs-size]Compiles Handlebars to HTML

Styling

NameStatusInstall SizeDescription
<style>![style-npm]![style-size]Add exports of a module as style to DOM
![css-npm]![css-size]Loads CSS file with resolved imports and returns CSS code
![less-npm]![less-size]Loads and compiles a LESS file
![sass-npm]![sass-size]Loads and compiles a Sass/SCSS file
![stylus-npm]![stylus-size]Loads and compiles a Stylus file
![postcss-npm]![postcss-size]Loads and transforms a CSS/SSS file using PostCSS

Frameworks

NameStatusInstall SizeDescription
![vue-npm]![vue-size]Loads and compiles Vue Components
![polymer-npm]![polymer-size]Process HTML & CSS with preprocessor of choice and require() Web Components like first-class modules
![angular-npm]![angular-size]Loads and compiles Angular 2 Components
![riot-npm]![riot-size]Riot official webpack loader

Performance

Webpack uses async I/O and has multiple caching levels. This makes webpack fast and incredibly fast on incremental compilations.

Module Formats

Webpack supports ES2015+, CommonJS and AMD modules out of the box. It performs clever static analysis on the AST of your code. It even has an evaluation engine to evaluate simple expressions. This allows you to support most existing libraries out of the box.

Code Splitting

Webpack allows you to split your codebase into multiple chunks. Chunks are loaded asynchronously at runtime. This reduces the initial loading time.

Optimizations

Webpack can do many optimizations to reduce the output size of your JavaScript by deduplicating frequently used modules, minifying, and giving you full control of what is loaded initially and what is loaded at runtime through code splitting. It can also make your code chunks cache friendly by using hashes.

Contributing

We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone. We have a vibrant ecosystem that spans beyond this single repo. We welcome you to check out any of the repositories in our organization or webpack-contrib organization which houses all of our loaders and plugins.

Contributions go far beyond pull requests and commits. Although we love giving you the opportunity to put your stamp on webpack, we also are thrilled to receive a variety of other contributions including:

  • Documentation updates, enhancements, designs, or bugfixes
  • Spelling or grammar fixes
  • README.md corrections or redesigns
  • Adding unit, or functional tests
  • Triaging GitHub issues -- especially determining whether an issue still persists or is reproducible.
  • Searching #webpack on twitter and helping someone else who needs help
  • Teaching others how to contribute to one of the many webpack's repos!
  • Blogging, speaking about, or creating tutorials about one of webpack's many features.
  • Helping others in our webpack gitter channel.

To get started have a look at our documentation on contributing.

If you are worried or don't know where to start, you can always reach out to Sean Larkin (@TheLarkInn) on Twitter or simply submit an issue and a maintainer can help give you guidance!

We have also started a series on our Medium Publication called The Contributor's Guide to webpack. We welcome you to read it and post any questions or responses if you still need help.

Looking to speak about webpack? We'd love to review your talk abstract/CFP! You can email it to webpack [at] opencollective [dot] com and we can give pointers or tips!!!

Creating your own plugins and loaders

If you create a loader or plugin, we would <3 for you to open source it, and put it on npm. We follow the x-loader, x-webpack-plugin naming convention.

Support

We consider webpack to be a low-level tool used not only individually but also layered beneath other awesome tools. Because of its flexibility, webpack isn't always the easiest entry-level solution, however we do believe it is the most powerful. That said, we're always looking for ways to improve and simplify the tool without compromising functionality. If you have any ideas on ways to accomplish this, we're all ears!

If you're just getting started, take a look at our new docs and concepts page. This has a high level overview that is great for beginners!!

Looking for webpack 1 docs? Please check out the old wiki, but note that this deprecated version is no longer supported.

If you want to discuss something or just need help, here is our Gitter room where there are always individuals looking to help out!

If you are still having difficulty, we would love for you to post a question to StackOverflow with the webpack tag. It is much easier to answer questions that include your webpack.config.js and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!)

If you are twitter savvy you can tweet #webpack with your question and someone should be able to reach out and help also.

If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on Github.

Sponsoring

Most of the core team members, webpack contributors and contributors in the ecosystem do this open source work in their free time. If you use webpack for a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth.

This is how we use the donations:

  • Allow the core team to work on webpack
  • Thank contributors if they invested a large amount of time in contributing
  • Support projects in the ecosystem that are of great value for users
  • Support projects that are voted most (work in progress)
  • Infrastructure cost
  • Fees for money handling

Author: Webpack
Source Code: https://github.com/webpack/webpack 
License: MIT License

#webpack #javascript 

Lawrence  Lesch

Lawrence Lesch

1642275180

Webpack: Packs Commonjs/AMD Modules for The Browser

webpack

Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

Table of Contents

  1. Install
  2. Introduction
  3. Concepts
  4. Contributing
  5. Support
  6. Core Team
  7. Sponsoring
  8. Premium Partners
  9. Other Backers and Sponsors
  10. Gold Sponsors
  11. Silver Sponsors
  12. Bronze Sponsors
  13. Backers
  14. Special Thanks

Install

Install with npm:

npm install --save-dev webpack

Install with yarn:

yarn add webpack --dev

Introduction

Webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

TL;DR

  • Bundles ES Modules, CommonJS, and AMD modules (even combined).
  • Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time).
  • Dependencies are resolved during compilation, reducing the runtime size.
  • Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc.
  • Highly modular plugin system to do whatever else your application requires.

Get Started

Check out webpack's quick Get Started guide and the other guides.

Browser Compatibility

Webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). Webpack also needs Promise for import() and require.ensure(). If you want to support older browsers, you will need to load a polyfill before using these expressions.

Concepts

Plugins

Webpack has a rich plugin interface. Most of the features within webpack itself use this plugin interface. This makes webpack very flexible.

NameStatusInstall SizeDescription
mini-css-extract-pluginmini-css-npmmini-css-sizeExtracts CSS into separate files. It creates a CSS file per JS file which contains CSS.
compression-webpack-plugincompression-npmcompression-sizePrepares compressed versions of assets to serve them with Content-Encoding
html-webpack-pluginhtml-plugin-npmhtml-plugin-sizeSimplifies creation of HTML files (index.html) to serve your bundles

Loaders

Webpack enables the use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node.js.

Loaders are activated by using loadername! prefixes in require() statements, or are automatically applied via regex from your webpack configuration.

Files

NameStatusInstall SizeDescription
val-loaderval-npmval-sizeExecutes code as module and considers exports as JS code

JSON

NameStatusInstall SizeDescription
cson-npmcson-sizeLoads and transpiles a CSON file

Transpiling

NameStatusInstall SizeDescription
babel-npmbabel-sizeLoads ES2015+ code and transpiles to ES5 using Babel
type-npmtype-sizeLoads TypeScript like JavaScript
coffee-npmcoffee-sizeLoads CoffeeScript like JavaScript

Templating

NameStatusInstall SizeDescription
html-npmhtml-sizeExports HTML as string, requires references to static resources
pug-npmpug-sizeLoads Pug templates and returns a function
md-npmmd-sizeCompiles Markdown to HTML
posthtml-npmposthtml-sizeLoads and transforms a HTML file using PostHTML
hbs-npmhbs-sizeCompiles Handlebars to HTML

Styling

NameStatusInstall SizeDescription
<style>style-npmstyle-sizeAdd exports of a module as style to DOM
css-npmcss-sizeLoads CSS file with resolved imports and returns CSS code
less-npmless-sizeLoads and compiles a LESS file
sass-npmsass-sizeLoads and compiles a Sass/SCSS file
stylus-npmstylus-sizeLoads and compiles a Stylus file
postcss-npmpostcss-sizeLoads and transforms a CSS/SSS file using PostCSS

Frameworks

NameStatusInstall SizeDescription
vue-npmvue-sizeLoads and compiles Vue Components
polymer-npmpolymer-sizeProcess HTML & CSS with preprocessor of choice and require() Web Components like first-class modules
angular-npmangular-sizeLoads and compiles Angular 2 Components
riot-npmriot-sizeRiot official webpack loader

Performance

Webpack uses async I/O and has multiple caching levels. This makes webpack fast and incredibly fast on incremental compilations.

Module Formats

Webpack supports ES2015+, CommonJS and AMD modules out of the box. It performs clever static analysis on the AST of your code. It even has an evaluation engine to evaluate simple expressions. This allows you to support most existing libraries out of the box.

Code Splitting

Webpack allows you to split your codebase into multiple chunks. Chunks are loaded asynchronously at runtime. This reduces the initial loading time.

Optimizations

Webpack can do many optimizations to reduce the output size of your JavaScript by deduplicating frequently used modules, minifying, and giving you full control of what is loaded initially and what is loaded at runtime through code splitting. It can also make your code chunks cache friendly by using hashes.

Contributing

We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone. We have a vibrant ecosystem that spans beyond this single repo. We welcome you to check out any of the repositories in our organization or webpack-contrib organization which houses all of our loaders and plugins.

Contributions go far beyond pull requests and commits. Although we love giving you the opportunity to put your stamp on webpack, we also are thrilled to receive a variety of other contributions including:

  • Documentation updates, enhancements, designs, or bugfixes
  • Spelling or grammar fixes
  • README.md corrections or redesigns
  • Adding unit, or functional tests
  • Triaging GitHub issues -- especially determining whether an issue still persists or is reproducible.
  • Searching #webpack on twitter and helping someone else who needs help
  • Teaching others how to contribute to one of the many webpack's repos!
  • Blogging, speaking about, or creating tutorials about one of webpack's many features.
  • Helping others in our webpack gitter channel.

To get started have a look at our documentation on contributing.

If you are worried or don't know where to start, you can always reach out to Sean Larkin (@TheLarkInn) on Twitter or simply submit an issue and a maintainer can help give you guidance!

We have also started a series on our Medium Publication called The Contributor's Guide to webpack. We welcome you to read it and post any questions or responses if you still need help.

Looking to speak about webpack? We'd love to review your talk abstract/CFP! You can email it to webpack [at] opencollective [dot] com and we can give pointers or tips!!!

Creating your own plugins and loaders

If you create a loader or plugin, we would <3 for you to open source it, and put it on npm. We follow the x-loader, x-webpack-plugin naming convention.

Support

We consider webpack to be a low-level tool used not only individually but also layered beneath other awesome tools. Because of its flexibility, webpack isn't always the easiest entry-level solution, however we do believe it is the most powerful. That said, we're always looking for ways to improve and simplify the tool without compromising functionality. If you have any ideas on ways to accomplish this, we're all ears!

If you're just getting started, take a look at our new docs and concepts page. This has a high level overview that is great for beginners!!

Looking for webpack 1 docs? Please check out the old wiki, but note that this deprecated version is no longer supported.

If you want to discuss something or just need help, here is our Gitter room where there are always individuals looking to help out!

If you are still having difficulty, we would love for you to post a question to StackOverflow with the webpack tag. It is much easier to answer questions that include your webpack.config.js and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!)

If you are twitter savvy you can tweet #webpack with your question and someone should be able to reach out and help also.

If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on Github.

Author: Webpack
Source Code: https://github.com/webpack/webpack 
License: MIT License

#webpack #javascript 

Easy Way to Save Outlook Email as PDF: - www.office.com/setup

If the user wants to save the Outlook Email message as PDF, then you must read this post. For installing Outlook app, just visit to the site of MS Office via www.office.com/setup get the office free key download 2021.

Save Email As PDF on Windows 10:

You should open the Outlook on your Windows 10 operating system and then sign in to your account. After this, browse your email messages and then open the one which you wish to save as a file in PDF format. Then, you should go to the ‘File’ tab which is in the ‘upper-left’ side of the screen and then click on it. Now, you should expand its options and then click on the ‘Print’ option. Here under the ‘Printer’ section, click on the ‘Microsoft Print to PDF’. Next, click on the ‘Print’ option and then press on the tab ‘Save Print Output As’. After this, you should drop down the options and then select the ‘PDF’ as the format of the saved file. At last, click on ‘Save’ option and then just close the ‘Email Message’.

Save Outlook 2010 Email As PDF:

You should open Outlook 2010 on your computer system and then log into your email account. Now, you should go to the ‘Inbox’, and then find and open the ‘Email message’ which you wish to save as a PDF file. Then, go within the ‘Email message’ and then click on ‘Control’ and ‘A’ keys at the same time on your keyboard. It will select the entire Email message together. Now, click on the ‘Control’ and ‘C’ keys at the same time on your keyboard just to copy the body of the ‘Email Message’. Here on the other hand, you should open a ‘New MS Office Word document’ and then click on ‘Control’ and ‘V’ key altogether on your keyboard. It will paste the email Message into the MS Word document. You should go to the ‘File’ and then click on the ‘Save’ option. At this point, you should browse the ‘Location’ button and then select a folder where you wish to save the PDF file of the Outlook Email message. Then, click on the ‘File Name’ and then enter a ‘Name’ just to identify the PDF file of the Outlook Email Message. At this point, you should click on the ‘Save As Type’ and then click on the ‘PDF’ option. After this, tap on ‘Save’ button which is in the lower-right side of the ‘Save As’ window and then just end the process. www office com setup

visit here this link: If “Unfortunately Android Keyboard has Stopped Error”! How to Fix it?

Save Outlook Mail as PDF On Mac:

You should open your Macbook Air and then go to the ‘Applications’ Menu and then just find the Outlook web app. Now, you should open the Outlook and then access your account and search for the email message which you wish to save as a PDF by the ‘Name’ or ‘Subject’ of the email. After this, go to the ‘File’ tab and then click on it just to expand its options. Then, tap on the option of ‘Print’ and then click on the ‘PDF’ just to expand the menu options. Here, click on the option ‘Save as PDF’. At this point, enter the ‘The name for the PDF file’ and then go to the next tab. Now in the ‘Save As field’ go to the folder and then select anyone according to your choice where you want to save it. At last, you should click on the ‘Save’ button.

For more details about Outlook Application, just visit to the site of MS Office via office.com/setup get the office free key 2021.

read here also…

www.webroot.com/safe
www.avg.com/retail

#save outlook email as pdf #www.office.com/setup #ms office #office.com/setup #office com setup #www office com setup

Hello Jay

Hello Jay

1602734922

How to Setup Webpack 5 from Scratch

Learn how to use webpack to bundle JavaScript, images, fonts, and styles for the web and set up a development server.

webpack used to be a frustrating and overwhelming beast to me. I felt safe using something like create-react-app to set up a project, but I avoided webpack if at all possible since it seemed complex and confusing.

If you don’t feel comfortable setting up webpack from scratch for use with Babel, TypeScript, Sass, React, or Vue, or don’t know why you might want to use webpack, then this is the perfect article for you. Like all things, once you delve in and learn it you realize it’s not that scary and there’s just a few main concepts to learn to get set up.

In addition to this article, I’ve created an extremely solid webpack 5 Boilerplate to get you started with any project. I also recommend checking it out if you’re familiar with webpack 4 but want to see a webpack 5 setup.

Prerequisites
  • Basic familiarity with HTML & CSS
  • Basic knowledge of JavaScript and programming
  • Familiarity with ES6 syntax and features
  • Ability to set up a Node.js environment
  • Knowledge of the command line
Goals
  • Learn what webpack is and why you might want to use it
  • Set up a development server with webpack
  • Set up a production build flow using webpack

#webpack #webpack 5 #html #css #javascript