search
HomeWeb Front-endJS TutorialHow to package js with webpack

How to package js with webpack

May 30, 2018 pm 05:45 PM
javascriptwebwebpack

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

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.

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

创建一个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"]
}

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

相关文章:

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
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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.