webpack基础学习+自定义封装AJAX类

webpack

本文用于记录webpack的简单使用,以及用原生JS封装XMLHttpRequest对象。

中文文档:webpack中文文档

  1. 首先生成package.json:npm init -y
  2. 安装webpack和webpack-cli:npm i webpack webpack-cli -D
  3. 新建一个webpack.config.js配置文件:
const path = require("path");
module.exports = {
    entry: "./src/app.js",//入口文件
    output: {//输出文件
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js"
    },
    mode: 'production'
}
  1. package.json文件的scripts对象内添加:"webpack": "webpack",如下:
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack"
  }
  1. 在index.html中引入bundle.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>webpack学习</title>
</head>
<body>
</body>
<script src="./dist/bundle.js"></script>
</html>
  1. 以后使用npm run webpack运行webpack命令

AJAX

文件结构:
QQ截图20190221190310.png
以下为ajax.js文件内容:

export default class Ajax {
    constructor() {
        this.xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");//兼任IE5及以下
    }
    send(options){
        let xhr = this.xhr;
        let opt = {
            type: options.type||"GET",
            url: options.url||"",
            async: options.async||"true",
            data: options.type == "POST" ? options.data||"" : ""
        }
        return new Promise(function(resolve, reject){
            xhr.open(opt.type, opt.url, opt.async);
            xhr.onreadystatechange = ()=>{
                if (xhr.readyState !== 4) {
                    return;
                  }
                  if (xhr.status === 200) {
                    resolve(xhr.response);
                  } else {
                    reject(new Error(xhr.statusText));
                  }
            }
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(opt.data);
        })
    }
}

使用方法,在app.js:

import xmlhttp from "./ajax";
let tianqi = new xmlhttp();
tianqi.send({
    type: "GET",
    url: "https://api.isoyu.com/index.php/api//Movie/playing_movie_list?start=0&count=9", 
}).then((value) => {
    console.log(value);
});

大致过程:创建一个Ajax类,构造函数中新建XMLHttpRequest对象,创建一个send方法,接收一个对象。使用Promise对象进行AJAX发送,并且返回这个Promise对象

0 评论