WebPack入门

发布时间 2023-09-10 14:36:10作者: 隔岸苦晴

什么是webpack

简单地说就是要一个web的打包工具,将项目所需要的资源进行打包处理。

安装webpack

很简单,首先是初始化一个node.js的项目

npm init

之后就是安装webpack以及webpack-cli

npm i webpack webpack-cli D

初试打包

我们在src/js目录下分别新建两个js文件,分别执行加法和减法操作
count.js

export default function count(x, y){
    return x - y
}

sum.js

export default function sum (...args){
    return args.reduce((p, c) => p + c, 0)
}

同时新建一个main.js来使用这上面了两个新建的js

import count from './js/count'
import sum from './js/sum'

console.log(count(2, 1))
console.log(sum(2, 1,3))

因为浏览器无法直接解析es6中的import语句,我们执行一下html代码时浏览器会报错

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello</h1>
    <script src="../src/main.js"></script>
</body>
</html>

这个时候,我们就需要将之前的js打包为一个或多个js来使其能被浏览器识别。执行以下代码来进行打包

npx webpack ./main.js --model=development

其中,npx的意思为执行node_modules\bin目录下的环境变量,使用webpack来对./main.js来进行打包,模式为开发模式development
打包完的文件在dist目录下的main.js,内容如下:

/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./src/js/count.js":
/*!*************************!*\
  !*** ./src/js/count.js ***!
  \*************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   \"default\": () => (/* binding */ count)\n/* harmony export */ });\nfunction count(x, y){\r\n    return x - y\r\n}\n\n//# sourceURL=webpack://webpack_study/./src/js/count.js?");

/***/ }),

/***/ "./src/js/sum.js":
/*!***********************!*\
  !*** ./src/js/sum.js ***!
  \***********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   \"default\": () => (/* binding */ sum)\n/* harmony export */ });\nfunction sum (...args){\r\n    return args.reduce((p, c) => p + c, 0)\r\n}\n\n//# sourceURL=webpack://webpack_study/./src/js/sum.js?");

/***/ }),

/***/ "./src/main.js":
/*!*********************!*\
  !*** ./src/main.js ***!
  \*********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _js_count__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./js/count */ \"./src/js/count.js\");\n/* harmony import */ var _js_sum__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./js/sum */ \"./src/js/sum.js\");\n\r\n\r\n\r\nconsole.log((0,_js_count__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(2, 1))\r\nconsole.log((0,_js_sum__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(2, 1,3))\n\n//# sourceURL=webpack://webpack_study/./src/main.js?");

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module can't be inlined because the eval devtool is used.
/******/ 	var __webpack_exports__ = __webpack_require__("./src/main.js");
/******/ 	
/******/ })()
;

配置文件

在根目录下设置配置文件webpack.conf.js,再有了配置文件之后,直接在控制台中输入npx webpack就可以开始打包了,再有配置文件时,会优先执行配置文件,没有的话在执行命令中的参数,一开始最简单的配置如下:

const path = require('path')    // nodejs的核心模块之一,用来处理路径问题

module.exports = {
    // 入口(绝对路径)
    entry: './src/main.js',
    // 输出
    output: {
        // 输出的路径(相对路径)
        // __dirnamem:当前文件的文件夹目录
        path: path.resolve(__dirname, 'dist'),
        // 文件名
        filename: 'main.js'
    },
    // 加载器
    module: {
        rules: [
            // loader的设置
        ],
    },
    // 插件
    plugins: [

    ],
    // 模式
    mode: "development"
}