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
Modularization allows us to refine complex programs into small files;
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;
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
webpack entry
output (command line) 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' } }
在命令行输入:webpack --config webpack.conf.js,发现生成了一个app.dd1c6.js带hash的js文件。将这个js文件引入HTML里面发正常输出:sum(21, 22) 43
配置文件的命名为webpack.config.js,则直接在命令行输入webpack就可以。
webapck配合babel打包ES6、7
在项目根目录安装bable-loader和babel-core,babel-preset
使用npm init生成一个配置文件
npm install babel-loader babel-core --save-dev
新建app.js,index.html,webpack.config.js等文件
编写webpack.config.js
安装babel-preset来指定编译的版本:npm install babel-preset-env --save-dev
在app.js里面随便写一些ES6的语法
使用命令行输入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处理,需要上面的两个插件)
Babel Polyfill(全局垫片),npm install babel-polyfill --save, 使用:import "babel-polyfill";
Babel Runtime Transform(为开发框架准备),npm install babel-plugin-transform-runtime --save, npm install babel-runtime --save
新建一个.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"] }
相关推荐:
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!

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.

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 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 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.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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 latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.
