vue3 + ali-oss将打包后的文件上传至oss流程步骤及脚本示例
安装ali-oss依赖包
npm i ali-oss -D
上传oss的脚本示例代码:
upload_oss.js文件
const OSS = require('ali-oss')
const fs = require('fs')
const path = require('path')
const os = require('os')
const DIST_PATH = path.join(__dirname, '/dist')
const client = new OSS({
accessKeyId: 'LTAI5tC6kWm346RJ8u1RJnqc', // oss右上角: AccessKey管理
accessKeySecret: 'B6eZA5c72NwpDhi5MQjf3HpmVW0WoA', // 此帐号只有upload-oss-vue的权限
bucket: 'upload-oss-vue',
region: 'oss-cn-guangzhou'
})
// 删除目录
const deleteDir = async dir => {
const result = await client.list({
'max-keys': 1000 // 最大查询1k条
})
if( result.objects.length === 0) return true
await client.deleteMulti(result.objects.map(obj => obj.name), {
quiet: true
})
console.log('删除完成')
return true
}
const uploadDir = (dir,oss_prefix = '/') => {
const docs = fs.readdirSync(dir)
docs.forEach(doc => {
const curr_src = dir + '/' +doc
const fs_src = fs.statSync(curr_src)
if( fs_src.isDirectory()){ // 文件夹 递归
uploadDir(curr_src,oss_prefix + doc + '/')
return
}
client.put( oss_prefix + doc,curr_src)
})
}
(async () => {
const del_res = await deleteDir(DIST_PATH)
if( del_res !== true) throw new Error('删除失败')
uploadDir(DIST_PATH)
console.log('上传完成')
})()
node(确保你有dist文件夹):
node upload_oss.js
优化上传
编辑 package.json, 添加prod命令 如下:
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 4173",
"prod":"vite build && node upload_oss"
}
运行prod:
npm run prod
效果:
相关文章