环境准备

1
2
npm install -g webpack webpack-cli
npm install crypto-js

项目结构

测试js脚本定义在js目录下,webpack.config.js在根目录

  • env.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29


    function check_env1() {
    return typeof window === 'undefined' ? "abcdef" : 'fedcba'
    }

    function check_env2() {
    return delete window ? '123456' : '654321';
    }

    function check_env3() {
    let key = '0000'
    try {
    key = typeof document.all[0] === 'ob' + 'ject' && !document.all ? '1234' : '9876'
    } catch (e) {
    key = '5678'
    }
    return key
    }


    function gen_key() {
    return check_env1() + check_env2() + check_env3()
    }


    module.exports = {
    gen_key
    }
  • enc.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const CryptoJS = require('crypto-js')

    function encrypt(plaintext, key) {
    let k = CryptoJS.enc.Utf8.parse(key);
    return CryptoJS.AES.encrypt(plaintext, k, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
    }).toString()
    }

    module.exports = {
    encrypt
    }
  • http.js(模拟入口)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    const { gen_key } = require('./env')
    const { encrypt } = require('./enc')

    function send_req() {
    let plaintext = 'hello world'
    let encrypted = encrypt(plaintext, gen_key())
    console.log('我发送了请求:', encrypted)
    }

    send_req()
  • webpack.config.js (注意路径)

    1
    2
    3
    4
    5
    6
    module.exports = {
    entry: "./js/http.js", // 入口
    output:{
    filename: "./js/app.js" // 打包后的文件输出到哪里
    }
    }
  • 在项目根目录执行 webpack 命令进行打包

  • 新建测试html,终端下测试输出

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./dist/js/app.js"></script>
    </head>
    <body>
    webpack
    </body>
    </html>