• webpack-PWA概念、typeScript打包、webpackDevServer实现请求转发


    PWA概念(Progressive Web Application):

    当我们服务器挂掉的时候,访问网站就会无法连接,PWA会在我们访问过后在本地生成一份缓存,即使服务器挂掉,我们在访问的时候还是可以看到之前缓存的内容,webpack中就有一个插件(google提供)可以帮我们做这件事:

    npm install workbox-webpack-plugin -D

    然后在webpack.prod.js中引入使用(我们只要在线上使用):

    const WorkboxPlugin=require('workbox-webpack-plugin');
    plugins:[
        new WorkboxPlugin.GenerateSW({
            clientsClaim:true,
            skipWaiting:true
        })
    ]

    还需要在业务代码中加上:

    if('serviceWorker' in navigator){
        window.addEventListener('load',()=>{
            navigator.serviceWorker.register('/service-worker.js')
            .then(registration=>{
                console.log('work');
                console.log(registration);
            }).catch(err=>{
                console.log(err);
            })
        })
    }

    typeScript打包配置:

    index.tsx:

    class Greeter{
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return 'hello' + this.greeting;
        }
    }
    
    let greeter = new Greeter('world');
    
    let button = document.createElement('button');
    button.textContent = 'say hello';
    button.onclick = function () {
        alert(greeter.greet());
    }
    
    document.body.appendChild(button);

    webpack.config.js配置:

    const path=require('path');
    
    module.exports={
        mode:'production',
        entry:'./src/index.tsx',
        module:{
            rules:[{
                test:/.tsx?$/,
                use:'ts-loader',
                exclude:/node_modules/
            }]
        },
        output:{
            filename:'bundle.js',
            path:path.resolve(__dirname,'dist')
        }
    }

    需要安装: npm i ts-loader typescript -D

    还需要有一个tsconfig.json,简单配置:

    {
        "compilerOptions": {
            "outDir": "./dist", // 打包生成文件的位置,可不写,已经在webpack中配置
            "module":"es6",
            "target":"es5", // 打包成es5的代码
            "allowJs":true, // 允许在ts中引入js模块
        }
    }

    打包就可以生成可用js

    当我们引入lodash,错误使用里面的join方法的时候: _.join(null); 并不会给我们错误提示,这就不符合我们的需求,我们可以通过安装lodash对应的类型文件进行解决:

    npm install @types/lodash -D

    我们引入的方式也要改变:

    import * as _ from 'lodash'

    我们可以从 https://microsoft.github.io/TypeSearch/ 搜索查看要使用的库可安装对应的类型文件

    webpackDevServer实现请求转发:

    在webpack.config.js中配置proxy:即可将请求转发到对应路径:

    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        hotOnly: true,
        proxy:{
            '/api':'http://www.request.com'
        }
    }

    在代码中只要使用如下代码就可以请求到上述地址中的接口(当然,接口中要做跨域配置):

    axios.get('/api/header.json').then(res=>{
        console.log(res);
    })

    在我们实际开发中,经常会遇到后台接口(header.json)没有开发完成,而是临时提供一个假数据(demo.json)的接口,那么我们是不是需要将业务中的header.json改成demo.json来实现呢?这样做也可以实现功能,但是容易忘记改回去或者不容易找到具体代码位置。实际上,我们也可以通过修改webpack配置来实现:

    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        hotOnly: true,
        proxy:{
            '/react/api':{
                target:'http://www.request.com',
                pathRewrite:{
                    'header.json':'demo.json'
                }
            }
        }
    }

    这个时候我们在业务中发起header.json的请求的时候就会去请求demo.json,等后台将接口完成以后,再将其删除或注释即可。 有时候我们请求的地址不是http,而是https,那么我们只需要增加一个配置:

    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        hotOnly: true,
        proxy:{
            '/react/api':{
                target:'https://www.request.com',
                secure:false,
                pathRewrite:{
                    'header.json':'demo.json'
                }
            }
        }
    }

    还有一个属性:

    proxy:{
        '/api':{
            target:'http://www.request.com',
            bypass: function(req, res, proxyOptions) {
                if (req.headers.accept.indexOf('html') !== -1) {
                    console.log('跳过转发');
                    return false;
                }
            },
            pathRewrite:{
                'header.json':'demo.json'
            }
        },
    }

    以上bypass的作用是当我们请求到的内容为html时,就跳过转发,请求到什么就返回什么

    当我们想要访问多个路径的情况下,可以设置:

    proxy:[{
        context:['/api','/auth'],
        target:'http://www.request.com'
    }]

    以上设置中不支持对根路径进行转发,如下不会生效:

    proxy:{
        '/':{
            target:'http://www.request.com'
        }
    }

    如果想要对根目录进行转发,需要设置index属性:

    proxy:{
        index:'',   // 或者 false
        '/':{
            target:'http://www.request.com'
        }
    }

    有些网站为了避免爬虫,做了origin的限制,如果只是用以上配置去请求接口,可能拿不到返回的内容,可以设置changeOrigin属性解决,建议在做代理转发的时候都加上此属性:

    proxy:{
        '/api':'http://www.request.com',
        changeOrigin:true
    }
  • 相关阅读:
    Web--js高级--12月19日随笔
    Web--js高级--12月18日随笔
    Web--js高级--12月17日随笔
    Web--js高级--关于所学闭包随笔
    Web--js高级--12月10日随笔
    Web--js高级--12月4日随笔
    Web--js高级--12月3日随笔
    微信小程序预览图片
    开发微信“小程序”必学教程
    navigator 页面链接
  • 原文地址:https://www.cnblogs.com/jingouli/p/12336029.html
Copyright © 2020-2023  润新知