webpack使用

一、什么是以及为什么要使用webpack

  现在的网页功能越来越丰富,所需要的JavaScript和模块也会很多,为开发更加简洁,出现了以下方法,如模块化,scss,typescript等。
但有些语法是浏览器无法识别的。所以需要用到webpack。
  WebPack是模块打包器,它会将浏览器不能支持不能识别的语言语法,打包转换成浏览器可识别的语法,如(Scss,TypeScript等)。

二、webpack 与 gulp 的区别

两者并无太多的可比性
1、webpack是为模块化提供解决方案;
2、gulp是前端自动化构建工具。

三、如何使用webpack

注:此例以webpack@3.5.3版本为例
另,热更新 服务器webpack-dev-server@2 依托以上版本

实例:

1、全局安装webpack

cnpm install webpack@3.5.3 -g
或
npm install webpack@3.5.3 -g

2、新建一个文件夹,并初始化文件

npm init -y

  之后,文件夹内会出现一个package.json 的文件

3、局部安装webpack

cnpm install webpack@3.5.3 --save-dev

  之后,文件夹会出现一个node_modules 的文件

4、新建webpack.config.js文件夹

5、创建 src 和dist 文件夹

6、src入口文件中新建index.js文件(书写需要的内容)如:

  

console.log(222)

7、配置webpack.config.js文件(配置基础部分)

// 引入核心模块
const path = require('path');

// __dirname:当前文件夹的绝对路径
// path.join:连接两个参数,生成新的路径
const PATH = {
    app:path.join(__dirname,'./src/index.js'),
    build:path.join(__dirname,'./dist')
}

// 测试,用node webpack.config.js 运行
// console.log(PATH.app)

// webpack配置项
module.exports = {
    entry:{
        // 入口路径,app名字决定下面出口文件的名字
        app:PATH.app
    },
    output:{
        filename:"[name].js",   //生成的出口文件名字为app.js
        path:PATH.build
    }
}

 cmd命令中,运行打包命令:

webpack

8、在dist中会生成一个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;
/******/
/******/     // 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 = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

console.log(222)

/***/ })
/******/ ]);

恭喜!至此,一次简单的打包完成!

但需要注意,以上打包方式仅适合4.0版本以下。4.0以上会有简单的变化。


9、当浏览器遇到不能识别的代码时,需要用到loader

  提前安装loader,在代码中解释

处理css的loader

               cnpm install --save-dev style-loader css-loader  sass-loader node-sass

处理js的loader

                cnpm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react

配置如下:

// 引入核心模块
const path = require('path');

// __dirname:当前文件夹的绝对路径
// path.join:连接两个参数,生成新的路径
const PATH = {
    app:path.join(__dirname,'./src/index.js'),
    build:path.join(__dirname,'./dist')
}

// 测试,用node webpack.config.js 运行
// console.log(PATH.app)

// webpack配置项
module.exports = {
    entry:{
        // 入口路径,app名字决定下面出口文件的名字
        app:PATH.app
    },
    output:{
        filename:"[name].js",   //生成的出口文件名字为app.js
        path:PATH.build
    },
    // 需提前配置好,解决浏览器不能识别的语法
    module:{
        rules:[
            {
                test:/.js$/,
                use:{
                    loader:'babel-loader',
                    options:{
                        presets:['@babel/env','@babel/react']
                    }
                }
            },
            {
                test:/.(css|scss)$/,
                use:['style-loader','css-loader','sass-loader']
            }
        ]
    }
}

  

  cmd命令中,运行打包命令:

webpack

  在dist 下新建一个index.html 文件,并引入app.js,即可实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script src="./app.js"></script>

现在,即可完成对不识别代码的识别,如ES6转为ES5等


以上为手动添加index,html文件

生成html模板(cmd命令)

插件
                cnpm install html-webpack-plugin --save-dev

webp新加plugins 配置

// 引入核心模块
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");

// __dirname:当前文件夹的绝对路径
// path.join:连接两个参数,生成新的路径
const PATH = {
    app:path.join(__dirname,'./src/index.js'),
    build:path.join(__dirname,'./dist')
}

// 测试,用node webpack.config.js 运行
// console.log(PATH.app)

// webpack配置项
module.exports = {
    entry:{
        // 入口路径,app名字决定下面出口文件的名字
        app:PATH.app
    },
    output:{
        filename:"[name].js",   //生成的出口文件名字为app.js
        path:PATH.build
    },
    // 需提前配置好,解决浏览器不能识别的语法
    module:{
        rules:[
            {
                test:/.js$/,
                use:{
                    loader:'babel-loader',
                    options:{
                        presets:['@babel/env','@babel/react']
                    }
                }
            },
            { 
                test:/.(css|scss)$/,
                use:['style-loader','css-loader','sass-loader']
            }
        ]
    },
    // 插件在plugins中使用
    plugins:[
        // HtmlWebpackPlugin 为构造函数
        new HtmlWebpackPlugin({
            // 生成的文件名称
            filename:'index.html',
            // 模板文件
            template:'./index.html',
        })
    ]
}

10、减少每次手动运行webpack,需要用热更新

cnpm install webpack-dev-server@2 --save-dev

在package.json 的 script中添加

"scripts": {
    "dev":"webpack-dev-server --open",
    "test": "echo "Error: no test specified" && exit 1"
  },

然后,cmd中运行

npm run dev

即可完成实时更新。。。。

注src 下的index.js 可导入其他文件,如:body.css,

  index.js:

import * as obj from './modeleW'

import './body.css'
console.log(222) console.log(obj.name) console.log(obj.age) console.log(obj.sign)

  body.css:

body{
    background: red;
}

手敲不易,肩膀疼,,,,,

原文地址:https://www.cnblogs.com/-roc/p/9989694.html