This time I will bring you webpack from initialization to use, and what are the precautions for webpack from initialization to use. The following is a practical case, let's take a look.
After installing node, create a new directory, such as html5. Switch to the current folder in cmd.
npm init -y
This command will create a default package.json. It contains some configuration parameters of the project through which initial installation can be performed. Detailed parameters: https://docs.npmjs.com/files/package.json.
If you don’t want the y parameter, you will set various parameters in the command box, but I don’t think it is necessary.
2. Install webpack
npm install webpack --save-dev
Install webpack to the current directory. Although npm install webpack -g can install webpack globally, it is prone to errors that some modules cannot be found, so it is best to install it in the current directory.
3. Directory structure
webpack is a module that loads various resources and packages them. So first create a directory structure as follows:
#app contains the js files under development, one component, and one entry. Build is used to store packaged files. webpack.config.js As the name suggests, it is used to configure webpack. Needless to say package.json.
component.js
export default function () { var element = document.createElement('h1'); element.innerHTML = 'Hello world'; return element; }
component.js outputs an h1 element with content. export default is ES6 syntax, which means specifying the default output. No need to include braces when importing.
index.js
import component from './component'; document.body.appendChild(component());
The function of index.js is to reference the Component module and output an h1 element on the page. But a plug-in is needed to complete this, because currently we do not have an index.html file.
npm install html-webpack-plugin --save-dev
html-webpack-plugin is used to generate html and install it in the development directory.
4. Set the webpack configuration file
We need to tell webpack how to start through the webpack.config.js file. A configuration file requires at least one entry and one output. Multiple pages require multiple entrances. node's path module
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const PATHS = { app: path.join(__dirname, 'app'), build: path.join(__dirname, 'build'), }; module.exports = { entry: { app: PATHS.app, }, output: { path: PATHS.build, filename: '[name].js', }, plugins: [ new HtmlWebpackPlugin({ title: 'Webpack demo', }), ], };
I was a little confused when I saw this configuration file for the first time. It is mainly exports, which is divided into three parts, an entrance, an output, and a plug-in. The entry points to the app folder. By default, the file containing "index.js" will be used as the entry. The output specifies the build address and a file name; [name] here represents a placeholder, which can be regarded as a variable provided by webpack. We’ll look at this later. The HtmlWebpackPlugin will generate a default html file.
5. Packaging
With the above preparations, you can directly enter webpack to run.
This output includes Hash (different packaging value each time), Version, Time (time-consuming). and output file information. At this time, open the build folder and find an additional app.js and index.html file. Double-click index.html:
You can also modify package.json
{ "name": "Html5", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "html-webpack-plugin": "^2.28.0", "webpack": "^2.2.1" } }
Specify build. Executing npm run build in cmd gets the same result
helloword appears. Look at the file content again
index.html:
nbsp;html> <meta> <title>Webpack demo</title> <script></script>
default references app.js.
6. Analysis
app.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = function () { var element = document.createElement('h1'); element.innerHTML = 'Hello world'; return element; }; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__component__ = __webpack_require__(0); document.body.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__component__["a" /* default */])()); /***/ }) /******/ ]);
And app.js has more content. The whole thing is an anonymous function.
(function(module) { })([(function (){}), function() {}])
The two js files in the app folder become the two modules here. The function starts from __webpack_require__
return __webpack_require__(__webpack_require__.s = 1);
Here it is specified to be executed from module 1 (the return value of the assignment statement is its value). The call to module 1 is executed through the sentence __webpack_require__.
Copy code The code is as follows:
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
Pass The main function of the call module is to pass parameters.
(function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__component__ = __webpack_require__(0); document.body.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__component__["a" /* default */])()); /***/ })
__webpack_require__ Every time a module is loaded, it will first be searched in the module cache. If not, a new module object will be created:
var module = installedModules[moduleId] = { i: moduleId, l: false, exports: {} };
模块1中加载了模块0,
var __WEBPACK_IMPORTED_MODULE_0__component__ = __webpack_require__(0);
__WEBPACK_IMPORTED_MODULE_0__component__ 返回的是这个模块0的exports部分。而之前Component.js的默认方法定义成了
__webpack_exports__["a"] = function () { var element = document.createElement('h1'); element.innerHTML = 'Hello world'; return element; }
所以再模块1的定义通过"a“来获取这个方法:
复制代码 代码如下:
document.body.appendChild(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__component__["a" /* default */])());
这样就完整了,但这里使用了__webpack_require__.i 将原值返回。
/******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; };
不太明白这个i函数有什么作用。这个注释也不太明白,路过的大神希望可以指点下。
小结:
webpack通过一个立即执行的匿名函数将各个开发模块作为参数初始化,每个js文件(module)对应一个编号,每个js中export的方法或者对象有各自指定的关键字。通过这种方式将所有的模块和接口方法管理起来。然后先加载最后的一个模块(应该是引用别的模块的模块),这样进而去触发别的模块的加载,使整个js运行起来。到这基本了解了webpack的功能和部分原理,但略显复杂,且没有感受到有多大的好处。继续探索。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of webpack from initialization to use. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment