Home Web Front-end JS Tutorial How to package js with webpack

How to package js with webpack

May 30, 2018 pm 05:45 PM
javascript web webpack

This article mainly introduces the method of packaging js with webpack. Now I will share it with you and give you a reference.

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.

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
Copy after login

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
Copy after login

Install webpack into the project

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

$ npm install --save-dev webpack
Copy after login

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;
}
Copy after login

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.

使用webapck的配置文件打包(还是上面的两个js文件)

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

// 配置文件使用commonjs规范

module.exports = {

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

  // 输出
  output: {
    // 带五位hash值的js
    filename: '[name].[hash:5].js'
  }
}
Copy after login

  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/' // 排除在外
      }
    ]
  }
}
Copy after login

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);
Copy after login

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() {
}
Copy after login

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/' // 排除在外
      }
    ]
  }
}
Copy after login

.babelrc文件配置

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

jQuery实现的上传图片本地预览效果简单示例

JavaScript面试出现频繁的一些易错点整理

vue axios请求拦截实例代码

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles