search
HomeWeb Front-endJS TutorialHow to use webpack modular management and packaging tool

This time I will show you how to use webpack modular management and packaging tools, and what are the precautions for using webpack modular management and packaging tools. The following is a practical case, let's take a look.

Introduction to Webpack

Webpack is currently the most popular front-end resource modular management and packaging tool. It can package many loose modules into front-end resources that are suitable for production environment deployment according to dependencies and rules. You can also code-separate modules loaded on demand and load them asynchronously when they are actually needed. Through loader conversion, any form of resource can be regarded as a module, such as CommonJs modules, AMD modules, ES6 modules, CSS, images, JSON, Coffeescript, LESS, etc.

Evolution of the module system<script>Tag</script>

<script></script>
<script></script>
<script></script>
<script></script>

This is the most original JavaScript file loading method. If each file is regarded as a module, then their interfaces are usually exposed In the global scope, that is, defined in the window object, the interface calls of different modules are all in the same scope. Some complex frameworks will use the concept of namespace to organize the interfaces of these modules. A typical example is the YUI library.

This original loading method exposes some obvious disadvantages:

It is easy to cause variable conflicts in the global scope

  1. Files can only be loaded in the writing order of <script></script>

  2. Developers must subjectively resolve the dependencies between modules and code libraries

  3. In large projects, various resources are difficult to manage, and long-term accumulated problems lead to a chaotic code base

  4. CommonJS specification

CommonJS is a project born with the goal of building a JavaScript ecosystem outside of browser environments, such as on servers and desktop environments. The CommonJS specification is a module form defined to solve the scope problem of JavaScript, allowing each module to execute in its own namespace. The main content of this specification is that modules must export external variables or interfaces through module.exports and import the output of other modules into the current module scope through require().

An intuitive example

// moduleA.js
module.exports = function( value ){
  return value * 2;
}
// moduleB.js
var multiplyBy2 = require('./moduleA');
var result = multiplyBy2(4);

AMD specification

AMD (Asynchronous Module Definition) is designed for browser environments , because the CommonJS module system is loaded synchronously, and the current browser environment is not ready to load modules synchronously. The module is defined in the closure through the define function, with the following format:

define(id?: String, dependencies?: String[], factory: Function|Object);

id is the name of the module, which is an optional parameter.

factory is the last parameter, which wraps the specific implementation of the module. It is a function or object. If it is a function, its return value is the output interface or value of the module.

Some use cases

Define a module named myModule, which depends on the jQuery module:

define('myModule', ['jquery'], function($) {
  // $ 是 jquery 模块的输出
  $('body').text('hello world');
}); // 使用 require(['myModule'], function(myModule) {});

Note: In webpack, the module name has only local scope. In Require. The module name in js has global scope and can be referenced globally.

Define an anonymous module without an id value, usually used as the startup function of the application:

define(['jquery'], function($) {
  $('body').text('hello world');
});

AMD also uses the require() statement to load the module, but unlike CommonJS, it requires two parameters

The first parameter [module] is an array, the members of which are the modules to be loaded; the second parameter callback is the callback function after successful loading. If the previous code is rewritten into AMD form, it will look like this:

math.add() and math module loading are not synchronized, and the browser will not freeze. So obviously, AMD is more suitable for browser environments

Currently, there are two main Javascript libraries that implement the AMD specification: require.js and curl.js

 require(['math'], function (math) {
    math.add(2, 3);
  });

What Is Webpack

#Webpack is a module bundler. It will perform static analysis based on module dependencies, and then generate corresponding static resources for these modules according to specified rules. Features of Webpack

Code Splitting

  1. Loader

  2. 智能解析

  3. 插件系统

  4. 快速运行

webpack基本使用

创建项目根目录

初始化

npm init 或 npm init -y

全局安装

npm install webpack -g

局部安装,在项目目录下安装

npm install webpack --save-dev

--save: 将安装的包的信息保存在package中

--dev:开发版本,只是项目构建的时候使用,项目构建完成后并不依赖的文件

如果使用web开发工具,单独安装

npm install webpack-dev-server --save-dev

基本使用

首先创建一个静态页面 index.html 和一个 JS 入口文件 entry.js:

<!-- index.html -->


<meta>


<script></script>

创建entry.js

// entry.js : 在页面中打印出一句话
document.write('It works.')

然后编译 entry.js并打包到 bundle.js文件中

// 使用npm命令 
webpack entry.js bundle.js

使用模块

1.创建模块module.js,在内部导出内容

module.exports = 'It works from module.js'

2.在entry.js中使用自定义的模块

//entry.js
document.write('It works.')
document.write(require('./module.js')) // 添加模块

加载css模块

1.安装css-loader

npm install css-loader style-loader --save-dev

2.创建css文件

//style.css
body { background: yellow; }

3.修改 entry.js:

require("!style-loader!css-loader!./style.css") // 载入 style.css
document.write('It works.')
document.write(require('./module.js'))

创建配置文件webpack.config.js

1.创建文件

var webpack = require('webpack')
module.exports = {
 entry: './entry.js',
 output: {
  path: __dirname,
  filename: 'bundle.js'
 },
 module: {
  loaders: [
    //同时简化 entry.js 中的 style.css 加载方式:require('./style.css')
   {test: /\.css$/, loader: 'style-loader!css-loader'}
  ]
 }
}

2.修改 entry.js 中的 style.css 加载方式:require('./style.css')

3.运行webpack

在命令行页面直接输入webpack

插件使用

1.插件安装

//添加注释的插件
npm install --save-devbannerplugin

2.配置文件的书写

var webpack = require('webpack')
module.exports = {
  entry: './entry.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      //同时简化 entry.js 中的 style.css 加载方式:require('./style.css')
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ],
    plugins: [
      //添加注释的插件
      new webpack.BannerPlugin('This file is created by zhaoda')
    ]
  }
}

3.运行webpack

// 可以在bundle.js的头部看到注释信息
/*! This file is created by zhaoda */

开发环境

webpack

--progress : 显示编译的进度

--colors : 带颜色显示,美化输出

--watch : 开启监视器,不用每次变化后都手动编译

12.4.7.1. webpack-dev-server

开启服务,以监听模式自动运行

1.安装包

npm install webpack-dev-server -g --save-dev

2.启动服务

实时监控页面并自动刷新

webpack-dev-server --progress --colors

自动编译

1.安装插件

npm install --save-dev html-webpack-plugin

2.在配置文件中导入包

var htmlWebpackPlugin = require('html-webpack-plugin')

3.在配置文件中使用插件

plugins: [
    //添加注释的插件
    new webpack.BannerPlugin('This file is created by zhaoda'),
    //自动编译
    new htmlWebpackPlugin({
      title: "index",
      filename: 'index.html', //在内存中生成的网页的名称
      template: './index.html' //生成网页名称的依据
    })
  ]

4.运行项目

webpack--save-dev

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

调用模式与this绑定

在实战项目中怎样使用jquery layur弹出层

The above is the detailed content of How to use webpack modular management and packaging tool. 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: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor