search
HomeWeb Front-endJS TutorialHow webpack packages js
How webpack packages jsMar 14, 2018 am 09:13 AM
javascriptwebwebpack

Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on module dependencies, and then generate corresponding static resources for these modules according to specified rules. This article mainly introduces the method of packaging js with webpack. Before practicing the code, let’s talk about the basic knowledge of webpack.

1. Why use WebPack

Many web pages today can actually be regarded as feature-rich applications. They have complex JavaScript codes and a lot of Dependency package. In order to simplify the complexity of development, many good practices have emerged in the front-end community

  1. Modularization allows us to refine complex programs into small files;

  2. Similar to TypeScript, a development language based on JavaScript: it allows us to implement features that cannot be used directly in the current version of JavaScript, and can later be installed into JavaScript files so that the browser can Recognition;

  3. Scss, less and other CSS preprocessors

2. What is Webpack

WebPack can be regarded as a module packager: what it does is to analyze your project structure and find JavaScript modules and other extension languages ​​​​that cannot be run directly by browsers. (Scss, TypeScript, etc.) and package it into a suitable format for browser consumption.

3. What are the characteristics of WebPack compared to Grunt and Gulp?

In fact, Webpack is not much comparable to the other two. Gulp/Grunt is a A tool that can optimize the front-end development process, and WebPack is a modular solution, but the advantages of Webpack allow Webpack to replace Gulp/Grunt tools.

The way Grunt and Gulp work is: in a configuration file, specify the specific steps to perform tasks such as compilation, combination, compression, etc. on certain files. This tool can then automatically complete these tasks for you.

These improvements have indeed greatly improved our development efficiency, but the files developed using them often require additional processing to be recognized by the browser, and manual processing is very anti-locking. This is Provides requirements for the emergence of tools like WebPack.

The way Webpack works is: treat your project as a whole, through a given main file (such as: index.js), Webpack will start from this file Find all the dependency files of your project, use loaders to process them, and finally package them into a JavaScript file that can be recognized by the browser.

We can see from the picture that Webpack can convert a variety of static resources js, css, and less into a static file, reducing page requests.

If you really want to compare the two, Webpack's processing speed is faster and more direct, and it can package more different types of files.

Next, we will briefly introduce
How Webpack merges multiple js files (note that this is just the merging of files, that is, merging multiple written js into one js file to reduce http requests).

Install webpack

Before installing Webpack, your local environment needs to support node.js. To install node.js, please refer to the official node documentation.

Use the following command to install webpack globally.


$ npm install webpack -g

webpack has been installed on your computer and you can now use the webpack command.

Use webpack in the project

Use the following command to generate the package.json file in the project root directory.


$ npm init

Install webpack into the project

Add webpack to the pageage.json configuration file, use the following command:


$ npm install --save-dev webpack

Look at the package.json file again at this time. Compared with when package.json was just created, a new piece of code has been added.


Two ways of webpack packaging

  1. webpack entry output (command line)

  2. webpack -config webpack.conf.js (specify webpack configuration file)

Use command line Packaging js

1: Create two js files

Create app.js, sum.js, export one sum.js Addition function, app.js uses this function.


// app.js

import {sum} from './sum';
console.log('sum(21, 22)', sum(21, 22));

// sum.js
export function sum(a, b) {
  return a + b;
}

Two: Use the webpack command to package

Use in the current directory: webpack app.js bundle.js ; The entry here is app.js, and the output file is bundle.js, so you will see an extra bundle.js file in the file.

Create an html file to run, introduce bundle.js to run, the console will print: sum(21, 22) 43.

Use webapck configuration file packaging (still the two js files above)

创建一个webpack.conf.js,编写wepack的配置文件


// 配置文件使用commonjs规范

module.exports = {

  // 入口,是一个对象
  entry: {
    app: './app.js'
  },

  // 输出
  output: {
    // 带五位hash值的js
    filename: '[name].[hash:5].js'
  }
}
  1. 在命令行输入:webpack --config webpack.conf.js,发现生成了一个app.dd1c6.js带hash的js文件。将这个js文件引入HTML里面发正常输出:sum(21, 22) 43

  2. 配置文件的命名为webpack.config.js,则直接在命令行输入webpack就可以。

webapck配合babel打包ES6、7

在项目根目录安装bable-loader和babel-core,babel-preset

  1. 使用npm init生成一个配置文件

  2. npm install babel-loader babel-core --save-dev

  3. 新建app.js,index.html,webpack.config.js等文件

  4. 编写webpack.config.js

  5. 安装babel-preset来指定编译的版本:npm install babel-preset-env --save-dev

  6. 在app.js里面随便写一些ES6的语法

  7. 使用命令行输入webpack进行编译

webpack配置文件


// 配置文件使用commonjs规范
module.exports = {

  // 入口,是一个对象
  entry: {
    app: './app.js' // 相对路径
  },

  // 输出
  output: {
    // 带五位hash值的js
    filename: '[name].[hash:8].js'
  },

  // 指定loader
  module: {

    // rules中的每一项是一个规则
    rules:[
      {
        test: /\.js$/, // 值一个正则,符合这些正则的资源会用一个loade来处理
        use: {
          loader: 'babel-loader', // 使用bable-loader来处理
          options: { // 指定参数
            presets: [
              ['babel-preset-env', {
                targets: {
                  browsers: ['> 1%', 'last 2 version'] //具体可以去babel-preset里面查看
                } 
              }]
              
            ] // 指定哪些语法编译
          }
        },
        exclude: '/node_module/' // 排除在外
      }
    ]
  }
}

app.js和编译之后带hash的js


// app.js
let func = () => {};
const num = 30;
let arr = [3, 4, 5, 6];

let newArr = arr.map(item => item * 2); // 将以前数组每一项*2

console.log(newArr);

// ==================//
// 编译之后(直接截取了编译的代码)
"use strict";


var func = function func() {};
var num = 30;
var arr = [3, 4, 5, 6];

var newArr = arr.map(function (item) {
 return item * 2;
}); // 将以前数组每一项*2

console.log(newArr);

babel的两个插件:Babel Polyfill 和 Babel Runtime Transform

用来处理一些函数和方法(Genertor,Set,Map,Array.from等未被babel处理,需要上面的两个插件)

  1. Babel Polyfill(全局垫片),npm install babel-polyfill --save, 使用:import "babel-polyfill";

  2. Babel Runtime Transform(为开发框架准备),npm install babel-plugin-transform-runtime --save, npm install babel-runtime --save

  3. 新建一个.babelrc来进行配置

app.js里面新增代码


import "babel-polyfill";
let func = () => {};
const num = 30; 
let arr = [3, 4, 5, 6];
let newArr = arr.map(item => item * 2); // 将以前数组每一项*2

console.log(newArr);
// 需要babel-polyfill
arr.includes(8);

// Genertor 函数
function* func2() {
}

webpack配置


// 配置文件使用commonjs规范
module.exports = {
  // 入口,是一个对象
  entry: {
    app: './app.js' // 相对路径
  },

  // 输出
  output: {
    // 带五位hash值的js
    filename: '[name].[hash:8].js'
  },

  // 指定loader
  module: {

    // rules中的每一项是一个规则
    rules:[
      {
        test: /\.js$/, // 值一个正则,符合这些正则的资源会用一个loade来处理
        use: {
          loader: 'babel-loader', // 使用bable-loader来处理
          options: { // 指定参数
            
          }
        },
        exclude: '/node_module/' // 排除在外
      }
    ]
  }
}

.babelrc文件配置


{
  "presets": [
    ["babel-preset-env", {
      "targets": {
        "browsers": ["> 1%", "last 2 version"]
      } 
    }] 
  ],
  "plugins": ["transform-runtime"]
}

相关推荐:

webpack打包之后的文件过大如何解决

webpack打包器的简单介绍

vue-cli快速构建vue应用并实现webpack打包详解

The above is the detailed content of How webpack packages js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool