Webpack

Webpack

Webpack is JavaScript module bundler. Webpack takes modules with dependencies and generates static assets representing those modules. Webpack's key features are rooted in extensibility and enabling developers to use best-practices in Web Architecture and Web Performance.

Webpack Boilerplate 3.0: A Sensible Webpack 5 Boilerplate

📦 webpack Boilerplate

Sensible webpack 5 boilerplate using Babel, PostCSS and Sass.

Installation

Clone this repo and npm install.

npm i

Usage

Development server

npm start

You can view the development server at localhost:8080.

Production build

npm run build

Note: Install http-server globally to deploy a simple server.

npm i -g http-server

You can view the deploy by creating a server in dist.

cd dist && http-server

Features

Dependencies

webpack

Babel

Loaders

Plugins

Linters

Download Details:
Author: taniarascia
Download Link: Download The Source Code
Official Website: https://github.com/taniarascia/webpack-boilerplate 
License: MIT
 

#webpack #html #css #webdev 

Webpack Boilerplate 3.0: A Sensible Webpack 5 Boilerplate
Reid  Rohan

Reid Rohan

1633942509

How to Set up a React project with Typescript, Hot reload, Webpack

React is one of the most popular libraries to build Single Page Applications. It has a huge community and many libraries built around it to solve a specific problem. One of those libraries is a boilerplate to quickly bootstrap a React application. Create-React-App is the most popular and comes out of the box with

  • Hot reload to promptly see the changes on the browser
  • Typescript supports
  • Set of tools to test your component
  • An optimized build for production
  • etc.…

Provides all these features implied the installation of many node packages, which can be a problem when you just want to start a project with the minimal configuration possible.

#typescript #webpack #react 

How to Set up a React project with Typescript, Hot reload, Webpack
Hoang  Ha

Hoang Ha

1632984748

Cách sử dụng Webpack để tạo một dự án làm việc với ReactJS

Tạo dự án với React + Webpack

Bài kế tiếp chúng ta sẽ học cách sử dụng công cụ "create-react-app" để tạo dự án làm việc với ReactJS. Tuy nhiên khi dùng "create-react-app" chúng ta chỉ cần chạy 1 command-line là xong, đôi khi điều này quá dễ dàng làm chúng ta không hiểu dự án đó được xây dựng như thế nào. Video này mình sẽ hướng dẫn cách bạn cách sử dụng Webpack để tạo một dự án làm việc với ReactJS. Video này rất phù hợp với các bạn muốn đào sâu hiểu bản chất của những thứ mình làm 😍😍😍

#react #webpack 

Cách sử dụng Webpack để tạo một dự án làm việc với ReactJS

Why To Use Webpack Module Bundler?

In this video, we can learn the reason why we should use Webpack Module Bundler.
1.  Problems we face with Regular Javascript Application
2.  Core Concepts of Webpack
3.  Three ways to generate the Dependency Graph 
Run the command "webpack --profile --json  webpack-stats.json" and import the json file in one of the below URLs to visualize the dependency graph.

#webpack #javascript 

 

Why To Use Webpack Module Bundler?

Introduce Unplugin: Unified Plugin System for Vite, Rollup and Webpack

unplugin

Experimental

Unified plugin system for build tools.

Currently supports:

Hooks

unplugin extends the excellent Rollup plugin API as the unified plugin interface and provides a compatible layer base on the build tools used with.

Supported

HookRollupViteWebpack
transformInclude
transform
enforce❌*
resolveId
load
  • *: Rollup does not support using enforce to control the order of plugins. Users will need to maintain the order manually.

Usage

import { createUnplugin } from 'unplugin'

export const unplugin = createUnplugin((options: UserOptions) => {
  return {
    name: 'my-first-unplugin',
    // webpack's id filter is outside of loader logic,
    // an additional hook is needed for better perf on webpack
    transformInclude (id) {
      return id.endsWith('.vue')
    },
    // just like rollup transform
    transform (code) {
      return code.replace(/<template>/, `<template><div>Injected</div>`)
    },
    // more hooks coming
  }
})

export const vitePlugin = unplugin.vite
export const rollupPlugin = unplugin.rollup
export const webpackPlugin = unplugin.webpack

Plugin Installation

Vite

// vite.config.ts
import MyUnplugin from './my-unplugin'

export default {
  plugins: [
    MyUnplugin.vite({ /* options */ })
  ]
}

Rollup

// rollup.config.js
import MyUnplugin from './my-unplugin'

export default {
  plugins: [
    MyUnplugin.rollup({ /* options */ })
  ]
}

Webpack

// webpack.config.js
module.exports = {
  plugins: [
    require('./my-unplugin').webpack({ /* options */ })
  ]
}

Framework-specific Logic

While unplugin provides compatible layers for some hooks, the functionality of it is limited to the common subset of the build's plugins capability. For more advanced framework-specific usages, unplugin provides an escape hatch for that.

export const unplugin = createUnplugin((options: UserOptions, meta) => {

  console.log(meta.framework) // 'vite' | 'rollup' | 'webpack'

  return {
    // common unplugin hooks
    name: 'my-first-unplugin',
    transformInclude (id) { /* ... */ },
    transform (code) { /* ... */  },
    
    // framework specific hooks
    vite: {
      // Vite config
      configureServer(server) {
        // configure Vite server
      }
    },
    rollup: {
      // Rollup config
    },
    webpack(compiler) {
      // configure Webpack compiler
    }
  }
})

Starter Templates

Examples

Download Details:
Author: unjs
Download Link: Download The Source Code
Official Website: https://github.com/unjs/unplugin
License: MIT
 

#vue #vite #rollup #webpack #webdev 

Introduce Unplugin: Unified Plugin System for Vite, Rollup and Webpack
Jake  Waters

Jake Waters

1629386460

How to Setup React using Webpack 5 & Babel Tutorial in 2021

In this video, we will set up React js without using the Create-React-App CLI.  We will create a React project from scratch using Webpack 5 and Babel.

#webpack #react 

How to Setup React using Webpack 5 & Babel Tutorial in 2021
Nandu Singh

Nandu Singh

1629292276

DOTENV Flow Webpack Plugin

dotenv-flow-webpack

A secure webpack plugin that gives the ability to access environment variables via process.env.* defined in your .env, .env.development, .env.test, .env.production, etc,. files within your web applications built with webpack.

Storing configuration in environment variables separate from code and grouping them by environments like development, test and production is based on The Twelve-Factor App methodology.

backed by dotenv-flow, inspired by dotenv-webpack

Installation

Using NPM:

$ npm install dotenv-flow-webpack --save-dev

Using Yarn:

$ yarn add dotenv-flow-webpack --dev

Description

Technically, the plugin wraps the dotenv-flow API providing the ability to configure it in your webpack.config.js file(s).

Note that plugin uses a secure strategy of replacing of the process.env.* code entries upon the build process, thus it exposes only environment variables that are used in your code.

Usage example

Let's suppose you have the following files in your project:

# .env

DATABASE_HOST=127.0.0.1
DATABASE_PORT=27017
DATABASE_USER=default
DATABASE_PASS=
DATABASE_NAME=my_app

SERVICE_URL=/api/v1
# .env.development

DATABASE_NAME=my_app_dev

SERVICE_URL=http://localhost:3000/api/v1
# .env.test

SERVICE_URL=https://localhost:3001/api/v1
# .env.production

DATABASE_HOST=10.0.0.32
DATABASE_PORT=27017
DATABASE_USER=devops
DATABASE_PASS=1qa2ws3ed4rf5tg6yh
DATABASE_NAME=application_storage

SERVICE_URL=https://myapp.com/api/v1
// webpack.config.js

const DotenvFlow = require('dotenv-flow-webpack');

module.exports = {
  // ...
  plugins: [
    new DotenvFlow()
  ],
  // ...
};
// file1.js

if (process.env.NODE_ENV !== 'production') {
  console.log(`Running in the "${process.env.NODE_ENV}" mode.`);
}
else {
  console.log('We are in production!');
}

const USERS_ENDPOINT = process.env.SERVICE_URL + '/users';

console.log('USERS_ENDPOINT:', USERS_ENDPOINT);

Thus, when you build your app with NODE_ENV=development, the resulting bundle will include something like this:

// file1.js

if (true) {
  console.log("Running in the ".concat("development", " mode."));
} else {}

const USERS_ENDPOINT = "http://localhost:3000/api/v1" + '/users';

console.log('USERS_ENDPOINT:', USERS_ENDPOINT);

Or if you build your app with NODE_ENV=production, then the output will look like:

// file1.js

if (false) {} else {
  console.log('We are in production!');
}

const USERS_ENDPOINT = "https://myapp.com/api/v1" + '/users';

console.log('USERS_ENDPOINT:', USERS_ENDPOINT);

And after all the optimization procedures it will be compressed till:

console.log("We are in production!");
console.log("USERS_ENDPOINT:", "https://myapp.com/api/v1/users");

Make a note that values of DATABASE_(HOST/PORT/USER/PASSWORD/NAME) will not be present in the resulting bundle while they are not referenced anywhere in the code.

Configuration

As a wrapper of dotenv-flow, dotenv-flow-webpack has the same configuration options extending them with its own described below.

options.node_env

Type: string

Default: process.env.NODE_ENV

By default, the plugin refers the NODE_ENV environment variable to detect the environment to use. With the node_env option you can force the module to use your custom environment value independent of process.env.NODE_ENV.

module.exports = (env, argv) => {
  // ...
  config.plugins.push(new DotenvFlow({
    node_env: env.production ? 'production' : 'development'
  }));
  // ...
};

options.default_node_env

Type: string

Default: undefined

If the NODE_ENV environment variable is not set, the module doesn't load/parse any NODE_ENV-specific files at all. Therefore, you may want to use "development" as the default environment.

new DotenvFlow({
  default_node_env: 'development'
})

options.path

Type: string

Default: process.cwd() (current working directory)

With the path initialization option you can specify a path to .env* files directory.

new DotenvFlow({
  path: '/path/to/env-files-dir'
})

If the option is not provided, the current working directory will be used.

options.encoding

Type: string

Default: 'utf8'

You can specify the encoding of your files containing environment variables.

new DotenvFlow({
  encoding: 'base64'
})

options.system_vars

Type: boolean

Default: false

If true, all the predefined process.env.* variables will also be loaded. In accordance to the dotenv-flow's specification, all the predefined system environment variables will have higher priority over the .env* files defined.

new DotenvFlow({
  system_vars: true
})

options.silent

Type: boolean

Default: false

Set to true to suppress all errors and warnings.

Additional information

Please refer the dotenv-flow documentation to learn more about the .env* files concept.

Here is the list of related sections:

Contributing

Feel free to dive in! Open an issue or submit PRs.

Running tests

Using NPM:

$ npm test

Using Yarn:

$ yarn test

License

Licensed under MIT © 2019-2020 Dan Kerimdzhanov

#dotenv #webpack 

DOTENV Flow Webpack Plugin
Nandu Singh

Nandu Singh

1629254080

How do remove console.log and comments in Webpack production

Remove Console.log From Prod Bundle using Webpack

Using terser-webpack-plugin

npm install terser-webpack-plugin --save-dev
optimization: {
    minimize: true,
    minimizer: [
    	new TerserPlugin({
        extractComments: true,
        cache: true,
        parallel: true,
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {          
           extractComments: 'all',
           compress: {
               drop_console: true,
           },
		}
      }),
    ],
  },

Using uglifyjs-webpack-plugin

npm install uglifyjs-webpack-plugin --save-dev
optimization: {
    minimize: true,
    minimizer: [
    	new UglifyJsPlugin({
      		uglifyOptions: {
        		output: {
          		// removing comments
          		comments: false,
        		},
        		compress: {
          		// remove warnings
          		warnings: false,
          		// remove console.logs
          		drop_console: true,
        		},
      		},
    	}),
    ],
  },

#webpack #javascript 

How do remove console.log and comments in Webpack production
NA SA

NA SA

1629166927

Dotenv Toml Webpack Plugin

dotenv-toml-webpack

A secure webpack plugin that gives the ability to access environment variables via process.env.* defined in your .env.toml, .env.development.toml, .env.production.toml, etc,. files within your web applications built with webpack.

Installation

Using NPM:

npm install dotenv-toml-webpack --save-dev

Using Yarn:

$ yarn add dotenv-toml-webpack --dev

Description

dotenv-toml-webpack wraps toml and Webpack.DefinePlugin. As such, it does a text replace in the resulting bundle for any instances of process.env.

Your .env.*.toml files can include sensitive information. Because of this, dotenv-toml-webpack will only expose environment variables that are explicitly referenced in your code to your final bundle.

Usage example

Let's suppose you have the following files in your project:

# .env.toml

API_URL = "http://localhost:8081"
BASE_URL = "http://localhost:8080"

[DB]
HOST = "127.0.0.1"
NAME = "mydb"
PASS = "1qa2ws3ed4rf5tg6yh"
PORT = 27017
USER = "sa"
// webpack.config.js

const EnvTomlPlugin = require('dotenv-toml-webpack');
// or
// const { EnvTomlPlugin } = require('dotenv-toml-webpack');

module.exports = {
  // ...
  plugins: [
    new EnvTomlPlugin()
  ],
  // ...
};

Use in your code

// file1.js
console.log(process.env.BASE_URL);
// 'http://localhost:8080'

console.log(process.env.DB.HOST);
// '127.0.0.1'

Resulting bundle

// bundle.js
console.log('http://localhost:8080');
console.log('127.0.0.1');

Note: the .env.*.toml values for BASE_URL and DB are NOT present in our bundle, as they were never referenced (as process.env.[VAR_NAME]) in the code.

How Secure?

By allowing you to define exactly where you are loading environment variables from and bundling only variables in your project that are explicitly referenced in your code, you can be sure that only what you need is included and you do not accidentally leak anything sensitive.

Recommended

Add .env.* to your .gitignore file

Env Webpack Mode

# .env.development.toml

API_URL = "http://localhost:8081"
BASE_URL = "http://localhost:8080"

[DB]
HOST = "127.0.0.1"
NAME = "mydb"
PASS = "123456"
PORT = 27017
USER = "sa"
# .env.production.toml

API_URL = "https://api.yourdomain.com"
BASE_URL = "https://yourdomain.com"

[DB]
HOST = "127.0.0.1"
NAME = "mydb"
PASS = "123456"
PORT = 27017
USER = "sa"
// webpack.config.js
module.exports = (env, argv) => {

    console.log(argv, env);
    const prod = argv.mode === 'production';    

    return {
        mode: 'development',
        target: 'web',
        devtool: prod ? false : 'source-map',
        plugins: [
            new EnvTomlPlugin({
                 path: `./.env.${argv.mode}.toml`,
            }),

        ],

    };
};

Properties

Use the following properties to configure your instance.

  • path ('./.env.toml') - The path to your environment variables.
  • systemvars (false) - Set to true if you would rather load all system variables as well (useful for CI purposes).
  • silent (false) - If true, all warnings will be suppressed.
  • safe (false) - If true, load '.env.example.toml' to verify the '.env' variables are all set. Can also be a string to a different file.

The following example shows how to set any/all arguments.

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: './.env.other.toml', // load this now instead of the ones in '.env'      
      systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
      silent: true, // hide any errors
      safe: true, // load '.env.example.toml' to verify the '.env' variables are all set. Can also be a string to a different file.
    })
  ]
  ...
};

Contributing

Please refer to each project's style and contribution guidelines for submitting patches and additions. In general, we follow the "fork-and-pull" Git workflow.

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull request so that we can review your changes

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

License

Licensed under MIT (c) 2021 Morioh Team

#webpack #toml #javascript #dotenv

Dotenv Toml Webpack Plugin
Nandu Singh

Nandu Singh

1629118555

Writing a Custom Webpack Plugin

Writing a Webpack Plugin

Plugins expose the full potential of the webpack engine to third-party developers. Using staged build callbacks, developers can introduce their own behaviors into the webpack build process. Building plugins is a bit more advanced than building loaders, because you'll need to understand some of the webpack low-level internals to hook into them. Be prepared to read some source code!

Creating a Webpack Plugin

A plugin for webpack consists of:

  • A named JavaScript function or a JavaScript class.
  • Defines apply method in its prototype.
  • Specifies an event hook to tap into.
  • Manipulates webpack internal instance specific data.
  • Invokes webpack provided callback after functionality is complete.
// A JavaScript class.
class MyExampleWebpackPlugin {
  // Define `apply` as its prototype method which is supplied with compiler as its argument
  apply(compiler) {
    // Specify the event hook to attach to
    compiler.hooks.emit.tapAsync(
      'MyExampleWebpackPlugin',
      (compilation, callback) => {
        console.log('This is an example plugin!');
        console.log(
          'Here’s the `compilation` object which represents a single build of assets:',
          compilation
        );

        // Manipulate the build using the plugin API provided by webpack
        compilation.addModule(/* ... */);

        callback();
      }
    );
  }
}

Basic plugin architecture

Plugins are instantiated objects with an apply method on their prototype. This apply method is called once by the webpack compiler while installing the plugin. The apply method is given a reference to the underlying webpack compiler, which grants access to compiler callbacks. A plugin is structured as follows:

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.done.tap(
      'Hello World Plugin',
      (
        stats /* stats is passed as an argument when done hook is tapped.  */
      ) => {
        console.log('Hello World!');
      }
    );
  }
}

module.exports = HelloWorldPlugin;

Then to use the plugin, include an instance in your webpack configuration plugins array:

// webpack.config.js
var HelloWorldPlugin = require('hello-world');

module.exports = {
  // ... configuration settings here ...
  plugins: [new HelloWorldPlugin({ options: true })],
};

Use schema-utils in order to validate the options being passed through the plugin options. Here is an example:

import { validate } from 'schema-utils';

// schema for options object
const schema = {
  type: 'object',
  properties: {
    test: {
      type: 'string',
    },
  },
};

export default class HelloWorldPlugin {
  constructor(options = {}) {
    validate(schema, options, {
      name: 'Hello World Plugin',
      baseDataPath: 'options',
    });
  }

  apply(compiler) {}
}

Compiler and Compilation

Among the two most important resources while developing plugins are the compiler and compilation objects. Understanding their roles is an important first step in extending the webpack engine.

class HelloCompilationPlugin {
  apply(compiler) {
    // Tap into compilation hook which gives compilation as argument to the callback function
    compiler.hooks.compilation.tap('HelloCompilationPlugin', (compilation) => {
      // Now we can tap into various hooks available through compilation
      compilation.hooks.optimize.tap('HelloCompilationPlugin', () => {
        console.log('Assets are being optimized.');
      });
    });
  }
}

module.exports = HelloCompilationPlugin;

The list of hooks available on the compiler, compilation, and other important objects, see the plugins API docs.

Async event hooks

Some plugin hooks are asynchronous. To tap into them, we can use tap method which will behave in synchronous manner or use one of tapAsync method or tapPromise method which are asynchronous methods.

tapAsync

When we use tapAsync method to tap into plugins, we need to call the callback function which is supplied as the last argument to our function.

class HelloAsyncPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync(
      'HelloAsyncPlugin',
      (compilation, callback) => {
        // Do something async...
        setTimeout(function () {
          console.log('Done with async work...');
          callback();
        }, 1000);
      }
    );
  }
}

module.exports = HelloAsyncPlugin;

tapPromise

When we use tapPromise method to tap into plugins, we need to return a promise which resolves when our asynchronous task is completed.

class HelloAsyncPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapPromise('HelloAsyncPlugin', (compilation) => {
      // return a Promise that resolves when we are done...
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          console.log('Done with async work...');
          resolve();
        }, 1000);
      });
    });
  }
}

module.exports = HelloAsyncPlugin;

Resources

https://webpack.js.org/contribute/writing-a-plugin/

https://webpack.js.org/api/plugins/

https://webpack.js.org/concepts/plugins/
 

#webpack #javascript 

Writing a Custom Webpack Plugin
Steve Griffith

Steve Griffith

1626979508

Getting Started with Webpack 5 in 2021

https://www.youtube.com/watch?v=9c3dBhvtt6o

Learn all the basics of Webpack 5 as well as the enhancements of version 5 over version 4.

#web-development #javascript #webpack #es6 #babel

Getting Started with Webpack 5 in 2021
Raleigh  Hayes

Raleigh Hayes

1626944700

Everything You Need To Know About Webpack | Webpack Tutorial

Hello! Today’s video is on webpack. Webpack is one of those things that I always need to relearn every time I have to work with it, so I thought I would share a quick tutorial to help me remember. This should cover the basics which are hopefully everything you need to know to get started. I hope you enjoy it :)

Useful Links:
GitHub: https://github.com/redhwannacef/youtube-tutorials/tree/master/webpack-tutorial

Timestamps:
0:00 - Intro
0:34 - Why We Need Webpack
4:02 - Adding Webpack To A Project
7:29 - Webpack Loaders
11:24 - Caching Files
13:50 - Webpack Plugins
16:29 - Webpack Dev Server
17:46 - Thank You For Watching

#webpack #webpack tutorial

Everything You Need To Know About Webpack | Webpack Tutorial
Talia  Lowe

Talia Lowe

1626466620

Webpack Basics Tutorial #6: Webpack Image Loaders NPM

#6 Webpack Image Loaders | Url Loader | Load Images with Webpack | Webpack Basics Tutorial | webpack tutorial for beginners | webpack 4 tutorial | webpack learn | image-loader npm | file-loader npm

https://github.com/imranhsayed/webpack-app/tree/image-loaders
https://medium.com/@imranhsayed/webpack-loaders-and-plugins-e13f79fe6b32

#webpack #npm

Webpack Basics Tutorial #6:  Webpack Image Loaders NPM
Talia  Lowe

Talia Lowe

1626430500

Webpack Basics Tutorial #5: Webpack Mini Css Extract Plugin NPM

Webpack Basics Tutorial #5: Webpack Mini Css Extract Plugin NPM

#5 Webpack Plugins | Mini Css Extract Plugin npm | Webpack Basics Tutorial | webpack tutorial for beginners | webpack 4 tutorial | webpack learn

https://github.com/imranhsayed/webpack-app/tree/mini-css-extract-plugins
https://medium.com/@imranhsayed/webpack-loaders-and-plugins-e13f79fe6b32

#npm #webpack #css

Webpack Basics Tutorial #5:  Webpack Mini Css Extract Plugin NPM
Talia  Lowe

Talia Lowe

1626419940

Webpack Basics Tutorial #4: Webpack Loaders

#4 Webpack Loaders | Hot Module Replacement | Style Loader | CSS Loader | Webpack Basics Tutorial | webpack tutorial for beginners | webpack 4 tutorial | webpack learn

https://github.com/imranhsayed/webpack-app/tree/style-and-css-loaders
https://medium.com/@imranhsayed/webpack-loaders-and-plugins-e13f79fe6b32

#webpack

Webpack Basics Tutorial #4:  Webpack Loaders