靜態資源打包工具Webpack入門與實戰

一、Webpack簡介

  webpack是一種打包工具,把前端項目中多個靜態資源(js、css、less)文件生成一個靜態文件,減少了頁面請求。
在這裏插入圖片描述

二、Webpack安裝

#全局安裝
npm install -g webpack webpack-cli 
#查看版本號
webpack -v

三、打包操作

(1)新建文件夾,進行項目初始化
npm init -y
(2)創建測試js文件

測試文件a.js

exports.info = function (str) {
    document.write(str);
}

測試文件b.js

exports.add = function (a, b) {
    return a + b;
}

主文件main.js

//引入打包的多個文件
const a= require('./a');
const b = require('./b');

a.info('Hello world!' + b.add(6, 6));
(3)創建配置文件,使用命令打包

webpack目錄下創建配置文件webpack.config.js

webpack目錄下創建dist輸出文件夾。

const path = require("path"); //Node.js內置模塊
module.exports = {
    entry: './src/main.js', //配置入口文件
    output: {
        path: path.resolve(__dirname, './dist'), //輸出路徑,__dirname:當前文件所在路徑
        filename: 'bundle.js' //輸出文件
    }
}
(4)終端執行webpack命令(不推薦)

打包成功,webpack目錄中dist文件會生成bundle.js文件!
在這裏插入圖片描述

(5)查看bundle.js文件
!function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=0)}([function(e,n,t){const r=t(1),o=t(2);r.info("Hello world!"+o.add(6,6))},function(e,n){n.info=function(e){document.write(e)}},function(e,n){n.add=function(e,n){return e+n}}]);
(6)終端執行webpack命令(推薦)
webpack #有黃色警告
webpack --mode=development #沒有警告
#執行後查看bundle.js 裏面包含了上面兩個js文件的內容並提醒了代碼壓縮

在這裏插入圖片描述

(7)瀏覽器執行
在webpack文件夾下新建test.html文件,右鍵選擇“open with live server”

<script src="./dist/bundle.js"></script>

在這裏插入圖片描述

♚學習、實戰、總結、分享,讓生活變得更美好!
☞林大俠博客:https://coding0110lin.blog.csdn.net/  歡迎轉載,一起技術交流探討!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章