vue/react前端项目自定义js脚本实现自定义部署等操作

因为项目需要,需要将同一个项目部署到四个不同的服务器上,并且每一个服务器的静态文件夹名称还不能一样,这就需要在打包之前,将静态文件夹重新命名,并且修改vue或者ts等文件中静态资源的引入路径,这是相当繁琐的意见事情,作为程序员,肯定忍不了这种事情发生。

所以,我的想法就是创建一个js脚本来实现这个工作,然后将这个脚本添加到package的script脚本下面,这样我就可以一键执行脚本来完成繁琐的工作。

所以该怎么做呢?

在项目的根目录下面创建deploy.js:

javascript 复制代码
const fs = require('fs')
const path = require('path')

// Function to copy a folder recursively
const copyFolderSync = (src, dest) => {
    if (!fs.existsSync(dest)) {
        fs.mkdirSync(dest, { recursive: true })
    }
    fs.readdirSync(src).forEach((item) => {
        const srcPath = path.join(src, item)
        const destPath = path.join(dest, item)
        if (fs.lstatSync(srcPath).isDirectory()) {
            copyFolderSync(srcPath, destPath)
        } else {
            fs.copyFileSync(srcPath, destPath)
        }
    })
}

// Function to update file references
const updateFileReferences = (dir, oldFolderName, newFolderName) => {
    const regex = new RegExp(`${oldFolderName}`, 'g')

    function updateFiles(dir) {
        fs.readdirSync(dir).forEach((file) => {
            const fullPath = path.join(dir, file)
            if (fs.statSync(fullPath).isDirectory()) {
                updateFiles(fullPath)
            } else if (
                file.endsWith('.js') ||
                file.endsWith('.vue') ||
                file.endsWith('.ts') ||
                file.endsWith('.scss') ||
                file.endsWith('.css') ||
                file.endsWith('.json')
            ) {
                let content = fs.readFileSync(fullPath, 'utf-8')
                if (
                    content.includes(`${oldFolderName}`) &&
                    newFolderName !== oldFolderName
                ) {
                    content = content.replace(regex, `${newFolderName}`)
                    fs.writeFileSync(fullPath, content)
                    console.log(`Updated references in: ${fullPath}`)
                }
            }
        })
    }
    updateFiles(dir)
}

// Main function to handle copying and renaming
const deployStaticFolder = (newFolderName) => {
    const srcFolder = path.join(__dirname, 'src', 'staticasap')
    const destFolder = path.join(__dirname, 'src', newFolderName)
    console.log('srcFolder', srcFolder, destFolder)

    if (fs.existsSync(srcFolder) && newFolderName !== 'staticasap') {
        copyFolderSync(srcFolder, destFolder)
        console.log(`Copied and renamed to: ${newFolderName}`)
        updateFileReferences(
            path.join(__dirname, 'src'),
            'staticasap',
            newFolderName
        )
    } else {
        console.error(
            'Source folder does not exist or newFolderName =',
            newFolderName
        )
    }
}

// update deploy time to index.html
const updateDeployTime = () => {
    const indexHtml = path.join(__dirname, 'index.html')
    let content = fs.readFileSync(indexHtml, 'utf-8')
    if (content.includes(`PUBLISHTIME`)) {
        var currentTime = new Date()
        console.log('currentTime', currentTime)
        content = content.replace('PUBLISHTIME', `${currentTime}`)
        fs.writeFileSync(indexHtml, content)
        console.log(`Updated time in: ${indexHtml}`)
    }
}

// update deploy time to index.html
const updateViteConfig = (newFolderName) => {
    const viteConfig = path.join(__dirname, 'vite.config.ts')
    let content = fs.readFileSync(viteConfig, 'utf-8')
    if (content.includes(`staticasap`) && newFolderName !== 'staticasap') {
        content = content.replaceAll('staticasap', newFolderName)
        fs.writeFileSync(viteConfig, content)
        console.log(`Updated vite config in: ${viteConfig}`)
    }
}

// delete dist folder
const deleteDistFolder = () => {
    const distFolder = path.join(__dirname, 'dist')
    if (fs.existsSync(distFolder)) {
        fs.rmdirSync(distFolder, { recursive: true })
        console.log(`Deleted folder: ${distFolder}`)
    } else {
        console.log(`Folder does not exist: ${distFolder}`)
    }
}

// deploy to server

// Get the new folder name from command line arguments
const newFolderName = process.argv[2]
console.log('new folder name', newFolderName)
if (newFolderName) {
    deleteDistFolder()
    updateDeployTime()
    updateViteConfig(newFolderName)
    deployStaticFolder(newFolderName)
} else {
    console.error('Please provide a new folder name.')
    process.exit(1)
}

其中代码的操作逻辑分为四个步骤:

1.拿到要修改静态资源文件夹名称

2.删除dist文件夹

3.更新vite配置

4.替换静态资源引入路径

5.自动部署dist文件夹到服务器中(待定)

然后将这个文件保存好,最后在pageckage里面添加脚本:

然后就可以一键执行来完成工作:

相关推荐
袁煦丞17 分钟前
跨平台终端王者Tabby:cpolar内网穿透实验室第632个成功挑战
前端·程序员·远程工作
Sailing19 分钟前
Grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
前端·node.js·mcp
阿山同学.38 分钟前
AWS 亚马逊 S3存储桶直传 前端demo 复制即可使用
前端·javascript·aws
Jolyne_1 小时前
grid 实现完美的水平铺满、间隔一致的自适应布局
前端·css
sunly_1 小时前
Flutter:导航固定背景图,滚动时导航颜色渐变
android·javascript·flutter
西洼工作室1 小时前
【解决导航栏字体图标渲染导致文本闪烁问题】采用腾讯视频的解决方案
前端·css·css3
摸鱼仙人~1 小时前
深入理解Java单例模式:确保类只有一个实例
java·javascript·单例模式
WindrunnerMax1 小时前
从零实现富文本编辑器#5-编辑器选区模型的状态结构表达
前端·架构·github
SteveDraw1 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
CodeSheep1 小时前
宇树科技,改名了!
前端·后端·程序员