Basic introduction to JavaScript webpack5 configuration and usage

WBOY
Release: 2022-09-05 17:24:48
forward
1964 people have browsed it

This article brings you relevant knowledge aboutjavascript. Webpack is a static module bundler (module bundler) for modern JavaScript applications. Let’s take a look at the configuration and use of JavaScript webpack5 Basic introduction, I hope it will be helpful to everyone.

Basic introduction to JavaScript webpack5 configuration and usage

[Related recommendations:javascript video tutorial,web front-end

1. webpack

1.1 Introduction

In the most original front-end development, we introduced files such as js and css by manually inserting script and link tags into html to achieve the purpose of citation. , which is not only cumbersome, but also requires a separate request for each file, and is prone to variable conflicts.

So the concept of JavaScript modularization was proposed, and solutions such as AMD, CommonJS, CMD, and ES6 modularization appeared in sequence.

But in fact, our project using modular development cannot run directly on the browser. For example, many npm modules use CommonJS syntax, which the browser does not support.

At this time, it is time for the module packaging tool to appear. Its task is to resolve the dependencies between modules and package the project into a JS file that the browser can recognize.

Currently popular packaging tools in the community include Webpack, Parcel, Rollup, etc.

If you have used scaffolding such as vue-cli or create-ract-app, then you have actually used webpack, because they are all secondary packaging based on webpack , Therefore, after mastering the principles of webpack, you can better develop vue and react engineering projects.

1.2 Five core concepts

The webpack configuration file in the project is located in the root directory:webpack.config.js

entry (entry)

The entry point indicates which module webpack should use as the beginning of building its internal dependency graph. For example, main.js in the vue project is the entry file when packaging.

module.exports = { entry: './src/main.js' };
Copy after login

All dependencies in the project should be directly or indirectly associated with the entry file. For example, we introduce external modules (axios, router, elementUI, etc.) in main.js. The

output (export)

outputattribute tells webpack where to output thebundlesit creates, and how to name these files. The default value is ./dist.

const path = require('path'); module.exports = { entry: './src/main.js', output: { //__dirname是当前目录根目录 path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' } };
Copy after login
  • The path attribute of ouput determines the location where the packaged files are generated. The default is ./dist. If not, webpack will automatically create this directory.
  • The filename attribute of ouput determines the name of the packaged file.

#loader

loader allows webpack to process non-JavaScript files (such as images, css files, vue files, etc., webpack itself only understands JavaScript).

Loader can convert all types of files into valid modules that webpack can process, and then you can use webpack's packaging capabilities to process them.

module.exports = { //... module: { rules: [ { test: /\.css$/, use: ['style-loader','css-loader'] } ] } };
Copy after login

When defining loader in webpack configuration, it must be defined in module.rules, where the test attribute is the regular file name that needs to be matched, and the use attribute is the corresponding loader, which can be multiple (array).

For example, the above style-loader and css-loader process the css files introduced in js (if you directly introduce css files into js, an error will be reported).

plugin

oader is used to convert certain types of modules, while plug-ins can be used to perform a wider range of tasks.

Plugins range from packaging optimization and compression to redefining variables in the environment. Plug-ins enhance the functionality of webpack.

To use plug-ins, for the plug-ins built into webpack, we can import webpack and directly access the built-in plug-ins. For external plug-ins, we need to install them first, then require them, and then introduce the plug-ins (new) in the plugin array. Example.

const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装 const webpack = require('webpack'); // 用于访问内置插件 const config = { module: { rules: [ //... ] }, plugins: [ new HtmlWebpackPlugin({template: './src/index.html'}) ] }; module.exports = config;
Copy after login

The above html-webpack-plugin plug-in automatically generates a corresponding html file in the packaged directory based on the template (template) page, and automatically inserts the script for packaging and generating js files. tag (normal webpack packaging does not generate html files).

mode (mode)

  • Development mode (development): optimize packaging speed and code debugging.
  • Production mode (production): optimize packaging speed, optimize code running performance

module.exports = { mode: 'production' };
Copy after login

That is, the packaging mode is different, then webpack has different requirements for packaging Code optimization strategies are also different.

2. Configuration and use

Let’s build a very simple webpack project.

Project structure

接着我们创建基本的项目结构和文件。

my-webpack-demo
├── src
| └── index.js(入口文件)
├── utils
| └── time.js(时间工具)
├── package-lock.json
├── package.json
├── webpack.config.js(webpack配置)

其中utils下的time.js负责生成当前时间 time.js:

var time = new Date(); var m = time.getMonth() + 1; var t = time.getFullYear() + "-" + m + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); module.exports = { now: t, };
Copy after login

入口文件index.js:

import { now } from "../utils/time.js"; document.write("现在是: " + now);
Copy after login

webpack配置文件webpack.config.js:

module.exports = { entry: "./src/index.js", mode: "development", output: { filename: "index.js", }, };
Copy after login

我们在终端执行打包命令:

此时webpack自动在项目中创建了dist目录,并生成了打包好的index.js文件,那么我们如何验证index.js文件是否有效呢?

使用html-webpack-plugin

由于webpack并不会自动生成html文件,还记得上面的html-webpack-plugin插件吗?

通过npm安装:

在配置文件中引入:

const HtmlWebpackPlugin = require("html-webpack-plugin"); // 通过 npm 安装 module.exports = { entry: "./src/index.js", mode: "development", output: { filename: "index.js", }, plugins: [new HtmlWebpackPlugin({ template: "./src/index.html", scriptLoading: "blocking" })], };
Copy after login

记得在src下创建index.html模板:

欧克!我们再次执行打包命令npx webpack

可以看到,在dist目录下不仅生成了index.js,还有index.html,我们在浏览器中打开它。

time.js成功生效咯 !

三、写在最后

我们完成了一个非常简单的webpack项目,你是否发现了这和vue项目的打包流程十分相似呢?

只是vue-cli的功能是十分强大的,例如可以解析vue文件,热更新等等……

所以这也验证了开始说的,vue-cli是对webpack的二次封装,封装了许多loader和plugin,并且配置好了入口,出口等配置信息,我们可以拿来就用。

【相关推荐:javascript视频教程web前端

The above is the detailed content of Basic introduction to JavaScript webpack5 configuration and usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!