1. 程式人生 > 實用技巧 >後臺模擬介面代理webpack實現

後臺模擬介面代理webpack實現

Webpack使用後臺代理開發入門

在專案根目錄下面新建main.js檔案,show.js檔案,package.json檔案,webpack.config.js,main.css檔案檔案

main.js檔案內容如下:

//引入css模組
require('./main.css');
import axios from 'axios'
//引入js
const show = require('./show.js');
show('webpack');

//後臺的介面
const URL = "/rest/plat/brmgr/v1/ui/baseinfo/products";
axios.get(URL).then(res => {
    console.log(res)
});

show.js檔案程式碼如下

function show(content) {
    window.document.getElementById('app').innerHTML = 'Helloeee,' + content;
}

module.exports = show;

package.json檔案程式碼如下

{
  "name": "webpack_Study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack --config webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^4.0.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "D": "^1.0.1",
    "axios": "^0.19.2"
  }
}

main.css檔案如下

#app{
    text-align: center;
}

webpack.config.js檔案如下

const path = require('path');
const proxyInfo = require(`./proxy_config.json`);
// const proxyList = ['/febs', '/unisess', '/rest', '/s', '/fonts', '/plugins', '/plat', '/eviewwebsite', '/fmwebsite', '/adminconsolewebsite', '/engrcommonwebsite'];
const proxyList = ['/rest'];
//rest開頭的介面使用環境上模擬的後臺介面
module.exports = {
    // JS 執行入口檔案
    entry: { main: './main.js', show: './show.js' },
    output: {
        // 把所有依賴的模組合併輸出到一個 bundle.js 檔案
        filename: '[name].js',
        // 輸出檔案都放到 dist 目錄下
        path: path.resolve(__dirname, './dist'),
    },
    module: {
        rules: [
            {
                // 用正則去匹配要用該 loader 轉換的 css 檔案
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            }
        ]
    },
    devServer: { // DevServer 相關的配置
        proxy: { // 代理到後端服務介面
            context: proxyList,
            target: `http://127.0.0.1:${proxyInfo.port}/localproxy`,
            changeOrigin: true,
        },
    }
};

在專案根目錄下面新建proxy_config.json,內容如下

{
    "port": 3333,
    "proxyConfig": [
        {
            "url": "https://9.2.23.67:31945/",
            "steps": [
                [
                    "input",
                    "#username",
                    "admin"
                ],
                [
                    "input",
                    "#value",
                    "***"
                ],
                [
                    "click",
                    "#submitDataverify"
                ]
            ],
            "title": "使用者登陸"
        }
    ],
    "ignoreUrls": [
        "/smapp/v1/settings/loginmode",
        "/rest/adminhome/website/v1/sitecustom"
    ]
}