Webpack notes

Webpack has five cores

// 1. EntryEntry refers to the file from which the Webpack starts packing// 2.Output means where does the webpack file Output go// 3. LoaderLoader can tell Webpack to process those JavaScript files because WebPack can only parse JavaScript files// 4. PluginsPlugins are plug-ins that you can use in a Webpack to achieve the desired effect// 5.Mode refers to the Mode in webpack, divided into developer Mode and production Mode.Copy the code

Basic use of Webpack

// Install NPM as an example:

// 1. Get package.json, also called initialization.Input instruction: NPM init// 2. Install webpack and scaffoldingEnter the command: NPM install webpack webpack-cli/ / 3. PackagingRun command: webpack js file to pack -o Path to pack --mode=development environment Take the development environment as an example: webpack./ SRC /index.js -o build/ --mode=developmentCopy the code

Configuration file for WebPack

// First you need to create a webpack.config.js file in the root directory

// You can then configure it in this file, as in the following simple example:

// Node has a built-in core module to handle path problems
const { resolve } = require('path');
// Configure webPack
module.exports = {
    // entries - Multiple entries can be configured, or detailed configurations can be made
    entry: './src/index.js'./ / output
    output: {
        // The output file name
        filename: './main.js'.// The path to the output file
        path: resolve(__dirname, 'build'),},// Loader configuration
    module: {
        rules: [
            // We will do some loader configuration here, and we will talk about it later]},/ / the plugin
    plugins: [
        // Configure some needed plugins here, and we'll talk about that later].// Mode - divided into developer mode and producer mode
    mode: 'development'.// Take developers as an example
};

// After a simple configuration, start with the command: webpack
Copy the code

How does WebPack package style resources?

// 1. You need to have style files first. Here, CSS and Scss are used as examplesThen import the style file in the js of the entry file:import './index.css';
import './index.scss';

// 2. Download the required loadernpm install style-loader css-loader sass-loader sass; Notice To use SCSS, you need to install sass-Loader and SASS// 3. Perform the following configuration in loader:
module: {
    rules: [
        // Configure loader here
        {
            // The matched file here ends in CSS
            test: /\.css$/.// Which loaders are used for processing
            // Loader is executed from bottom to top and from right to left
            use: [
                // style-loader does the following:
                // Create a style tag that inserts the js style resource into the HTML head
                'style-loader'.// csS-loader does the following:
                // Change the CSS file into a commonJS module and load it into js with strings
                'css-loader'] {},test: /\.(scss|sass)$/,
            use: [
                'style-loader'.'css-loader'.// Since it is SCSS, SCSS must be compiled to CSS
                'sass-loader']]}},Copy the code

Webpack packages HTML resources

// 1. First, you need an HTML template. The original template is good

// 2. Then you need to use one of the five cores in Webpack "plug-in", install the plug-in:
npm install html-webpack-plugin

// 3. Import the installed plug-in
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 4. Use webpack plugins as follows:
plugins: [
    new HtmlWebpackPlugin({
        // Indicates which HTML template to copy
        template: './src/index.html'}),].Copy the code

Webpack packs image resources

// 1. Create an images file to store images

// 2. Download the loader that processes image resources
npm install html-loader url-loader file-loader

// 3. Configure the Loader in WebPack
module: {
    rules: [
        // Configure loader here
        {
            // Image processing - here we currently match PNG and JPG
            test: /\.(png|jpg)$/.// A loader is used here, so it can be written like this
            loader: 'url-loader'.options: {
                // Images smaller than 8KB will be base64 processed
                limit: 8 * 1024.// Rename the image
                name: '[hash:10].[ext]'.// Make sure there are no Spaces between them}},// It doesn't work up to this point, as it can only handle images in JS
        // Images in HTML are still not valid
        // Add an additional loader for processing -html-loader
        {
            test: /\.html$/.// Process the IMG image of the HTML file
            loader: 'html-loader',},... ] }Copy the code

Hot update to Webpack

// 1. Install NPM I webpack-dev-server

// 2. Configure it in webpack.config.js
module.exports = {
    ......
    // Hot update to webpack
    devServer: {
        // The path to the packaged project
        contentBase: resolve(__dirname, 'build'),
        // Start gzip compression
        compress: true./ / the port number
        port: 3000.// Automatically open the browser
        open: true,}};// 3. Run the NPX webpack server command to start
Copy the code

Extract the CSS styles from the packaged JS file into a separate file

// 1. Install mini-css-extract-plugin

// 2. Introduce plug-ins
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// 3. Perform the configuration in webpack.config.js
plugins: [
    new MiniCssExtractPlugin({
        // Rename the output CSS file
        filename: 'css/index.css'}),... ]// 4. Use the loader in MiniCssExtractPlugin for processing
module: {
    rules: [{test: /\.css$/,
            use: [
                // This loader replaces style-loader to extract styles from js
                MiniCssExtractPlugin.loader,
                'css-loader']},... ] }Copy the code

Style compatibility handling

// 1. Install NPM install postCSs-loader postCSs-preset -env

// 2. Set the nodejs environment variable - no write means production mode
process.env.NODE_ENV = 'development';	

// 3. Configure webpack.config.js
module: {
    rules: [{test: /\.css$/,
            use: [
                // This loader replaces style-loader to extract styles from js
                MiniCssExtractPlugin.loader,
                'css-loader',
                {
                    loader: 'postcss-loader'.options: {
                        // Go to Githup for the latest version
                        postcssOptions: {
                            plugins: [["postcss-preset-env"],],}}},]},...... ] }// 4. Configure the browser compatible version in package.json
"browserslist": {
    "development": [
      "last 1 chrome version"."last 1 firefox version"."last 1 safari version". Can be additional configured],"production": [
      "0.2%" >."not dead"."not op_mini all". Additional configuration is possible]}Copy the code

JavaSrcipt compatibility processing

// 1. Install NPM install babel-loader @babel/ core@babel /preset-env core-js

// 2. Configure in webpack.config.js
module: {
    rules: [
        // Configure loader here
        {
            test: /\.js$/.// Exclude js code not written by yourself
            exclude: /node_modules/,
            loader: 'babel-loader'.options: {
                presets: [['@babel/preset-env',
                        {
                            // Load as needed
                            useBuiltIns: 'usage'.// Specify the core-js version
                            corejs: {
                                version: 3,},// Specify which version is compatible
                            targets: {
                                chrome: '60'.ie: '9'}},]]}},]}Copy the code