Asset Building using Webpack & Babel
Webpack
Webpack is an open-source JavaScript module bundler. Even though it is primarily a module bundler for JavaScript, it can transform front-end assets like HTML, CSS, and images if the corresponding plugins are included. Webpack takes modules with dependencies and generates static assets representing those modules.
Understanding WebPack
Here are a few resources for you to get started –
- Documentation
- How does Webpack work?
- Setting Up Webpack for your project
- Webpack Loaders & Plugins
- Webpack Dev Server
Babel
Babel or Babel.js is a free and open-source JavaScript compiler and configurable transpiler used in web development.
@wordpress/scripts
wp-scripts is a powerful toolset that streamlines your WordPress development workflow, particularly when working with modern JavaScript features and build processes. It provides a set of pre-configured scripts and configurations to handle tasks like:
- Compiling JavaScript and CSS: Transpiling modern JavaScript (ES6+) and pre-processing CSS (Sass, Less) into browser-compatible formats.
- Bundling Assets: Combining multiple files into smaller bundles to optimize performance.
- Minifying Files: Reducing file sizes for faster loading times.
- Creating Production Builds: Generating optimized builds for deployment to production environments.
Basic Setup
Install the Package:
npm install --save-dev @wordpress/scripts
Configure package.json
{
"scripts": {
"start": "wp-scripts start src/index.js",
"build": "wp-scripts build src/index.js"
},
"devDependencies": {
"@wordpress/scripts": "^[replace-with-latest-version]"
}
}
Basic JavaScript File (src/index.js):
import { registerBlockType } from '@wordpress/blocks';
registerBlockType( 'my-plugin/my-block', {
title: 'My Block',
edit: () => {
return <p>Hello, world!</p>;
},
save: () => {
return <p>Hello, world!</p>;
},
} );
Running the Scripts:
Run following commands from terminal.
# Development
npm start
# Build
npm run build
Ideas to Explore:
- What is Webpack? How does it work? How to set it up?
- What are loaders and plugins in the context of Webpack? Whats their purpose?
- What is Babel? How does it work? How to set it up?
- What are “Presets” in babel?
- What is a polyfill?
- In which scenario can Webpack be used without Babel?
- Do we need Babel while build command-line interfaces? If yes, then why? If no, then why not?