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:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Webpack demo</title> </head> <body> <script type="text/javascript" src="app.js"></script></body> </html>
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!