通义灵码-搭建js在线压缩网页

通义灵码-搭建js在线压缩网页

使用背景

使用js代码编写浏览器插件,部署的时候需要压缩js代码,为了方便使用,在自己的服务器上搭建一个js代码压缩工具。
AI编码工具在最近比较流行,我也使用阿里的“通义灵码”体验一下。效率不错,分享下过程。

开发步骤
  • 开发工具 VSCode(打开vscode,Ctrl+Shift+P,输入configure language就会出现自带的语言设置选项了,可修改为中文。)

  • 打开插件页面,搜索通义灵码(TONGYI Lingma),找到通义灵码后点击安装。
    在这里插入图片描述

  • 本地创建文件夹jscompress(文件夹名称可以自己定义),在vscode中打开该文件夹。在页面的左侧菜单能看到“通义灵码”的菜单。点击登录“个人版”,会打开浏览器,网页上输入用户名和密码(没有账号可以注册一个)。
    在这里插入图片描述

  • 登录成功以后网页会提示“登录成功”,再回到vscode就可以使用了。
    在这里插入图片描述

  • 和聊天一样,我简单描述了任务:我想个人服务器上部署一个在线压缩js代码的网页,能显示压缩前后的代码,能下载压缩后的代码,谢谢!(可以更详细一些,我只需要简单的压缩,所以要求很简单。)
    在这里插入图片描述

  • 基本内容是:后端部分 (Node.js + Express + Terser);前端 (HTML + JavaScript);

  • 默认服务器是linux系统,后端(Node.js + Express),先安装npm,node.js(这个也可以问AI,重点不在这里我就不展示了)。将代码根据推荐的文件名保存到本地。

服务端 server.js:

const express = require('express');
const Terser = require('terser');
const app = express();
const port = 3000;

app.use(express.json({ limit: '5mb' }));

app.post('/compress', async (req, res) => {
    const { code } = req.body;
    if (!code) {
        return res.status(400).json({ error: 'No code provided' });
    }
    try {
        const compressed = await Terser.minify(code);
        if (compressed.error) {
            return res.status(500).json({ error: compressed.error.message });
        }
        res.json({ compressedCode: compressed.code });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

app.use(express.static('public'));

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

前端代码 index.html(相关的js代码直接写到了html文件):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Code Compressor</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        textarea {
            width: 100%;
            height: 200px;
            margin-bottom: 10px;
        }
        button {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>JS Code Compressor</h1>
    <input type="file" id="fileInput" accept=".js">
    <button onclick="compressFile()">Compress</button>
    <button onclick="downloadCompressedFile()">Download Compressed File</button>
    <h2>Original Code</h2>
    <textarea id="originalCode" readonly></textarea>
    <h2>Compressed Code</h2>
    <textarea id="compressedCode" readonly></textarea>

    <script>
        let originalCode = '';

        document.getElementById('fileInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    originalCode = e.target.result;
                    document.getElementById('originalCode').value = originalCode;
                };
                reader.readAsText(file);
            }
        });

        async function compressFile() {
            if (!originalCode) {
                alert('Please upload a JS file first.');
                return;
            }
            try {
                const response = await fetch('/compress', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ code: originalCode })
                });
                const result = await response.json();
                if (result.error) {
                    alert('Error compressing code: ' + result.error);
                } else {
                    document.getElementById('compressedCode').value = result.compressedCode;
                }
            } catch (error) {
                alert('Error compressing code: ' + error.message);
            }
        }

        function downloadCompressedFile() {
            const compressedCode = document.getElementById('compressedCode').value;
            if (!compressedCode) {
                alert('Please compress the code first.');
                return;
            }
            const blob = new Blob([compressedCode], { type: 'text/javascript' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'compressed.js';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    </script>
</body>
</html>

创建public文件夹,将index.html文件放入public文件夹( 因为:app.use(express.static(‘public’)); )。
在这里插入图片描述

  • 部署到服务器。复制 jscompress文件夹到服务器上,进入jscompress目录,然后安装相关环境。
cd jscpmpress
npm init -y
npm install express terser
  • 安装完成后,运行服务:
node server.js

提示:Server running at http://localhost:3000(远程服务器上记得打开相应的端口)

  • 访问页面,我的页面如下图:
    在这里插入图片描述

  • 点击“选择文件”->点击“Compress”按钮,就能看到原始代码和压缩后的代码:
    在这里插入图片描述

  • 点击“Download Compressed File”按钮即可下载文件:
    在这里插入图片描述

  • 下载文件默认的名称是compressed.js我不是很满意,我继续和AI对话:
    在这里插入图片描述
    在这里插入图片描述

  • 修改后的index.html文件如下,下载文件的名称会在原始文件名的基础上加上后缀“.min”:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Code Compressor</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        textarea {
            width: 100%;
            height: 200px;
            margin-bottom: 10px;
        }

        button {
            margin-right: 10px;
        }
    </style>
</head>

<body>
    <h1>JS Code Compressor</h1>
    <input type="file" id="fileInput" accept=".js">
    <button onclick="compressFile()">Compress</button>
    <button onclick="downloadCompressedFile()">Download Compressed File</button>
    <h2>Original Code</h2>
    <textarea id="originalCode" readonly></textarea>
    <h2>Compressed Code</h2>
    <textarea id="compressedCode" readonly></textarea>

    <script>
        let originalCode = '';
        let fileName = '';

        document.getElementById('fileInput').addEventListener('change', function (event) {
            const file = event.target.files[0];
            if (file) {
                fileName = file.name.replace(/\.[^/.]+$/, ''); // Remove file extension
                const reader = new FileReader();
                reader.onload = function (e) {
                    originalCode = e.target.result;
                    document.getElementById('originalCode').value = originalCode;
                };
                reader.readAsText(file);
            }
        });

        async function compressFile() {
            if (!originalCode) {
                alert('Please upload a JS file first.');
                return;
            }
            try {
                const response = await fetch('/compress', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ code: originalCode })
                });
                const result = await response.json();
                if (result.error) {
                    alert('Error compressing code: ' + result.error);
                } else {
                    document.getElementById('compressedCode').value = result.compressedCode;
                }
            } catch (error) {
                alert('Error compressing code: ' + error.message);
            }
        }

        function downloadCompressedFile() {
            const compressedCode = document.getElementById('compressedCode').value;
            if (!compressedCode) {
                alert('Please compress the code first.');
                return;
            }
            const blob = new Blob([compressedCode], { type: 'text/javascript' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName + '.min.js'; // Use the original file name with .min.js extension
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    </script>
</body>

</html>
  • 代码已经满足了压缩js代码的简单要求,我的“通义灵码”帮我搭建js在线压缩工具的过程就结束了。
总结

每个人使用的AI编程工具会不同,我没有特别推荐。使用工具过程中AI的返回结果可能不一样,和AI的沟通也要慢慢去磨合,体验AI编程,拥抱AI编程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值