# 【优化】-图片自动上传oss-plugin
# 场景
一开始接手小程序项目的时候发现包体积过大导致不可以预览,然后发现项目中存放了大量的图片,占用了很大的体积。但是把图片一张一张的迁移到oss有点麻烦,就撸了一个图片自动上传oss的plugin
# 实施
首先我们来看下plugin的代码
const fs = require('fs')
const OSS = require('ali-oss')
const imgPath = 'dist'
function sleep() { // 延迟睡眠函数
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 500)
})
}
async function uploadImg(files) {
const client = new OSS({ // OSS相关的参数
region: 'xxxxxxxxxxxxxxxx',
accessKeyId: 'xxxxxxxxxxxxxxxx',
accessKeySecret: 'xxxxxxxxxxxxxxxx',
bucket: 'xxxxxxxxxxxxxxxx',
})
for (let i = 0, len = files.length; i < len; i++) { // 将dist包中common下存放的图片全部上传oss
await client.put(`common/${files[i]}`, `${imgPath}/common/${files[i]}`)
await sleep()
}
for (let i = 0, len = files.length; i < len; i++) { // 删除dist包中的图片
fs.unlinkSync(`${imgPath}/common/${files[i]}`)
}
console.log('\x1B[44m%s\x1B[49m', 'upload img fished>>>>>>>>>>>>>>>')
}
class OssPlugin {
apply(compiler) {
compiler.hooks.afterEmit.tapAsync('done', (compilation, callback) => {
fs.readdir(`${imgPath}/common`, (err, files) => { // 读取dist/common下的全部图片
if (err) {
console.error(err)
} else {
uploadImg(files)
}
})
callback()
})
}
}
module.exports = OssPlugin
这样的话我们就实现了一个简单的自动上传图片到oss的webpack-plugin,但是还不够,我们还需要url-loader
的配合,因为我们需要将图片打包到dist/common并且将相关的图片引用如src="../../img/xxx.png"
转化为我们oss的地址src="xxxx/xx.png"
// webpack.config.js
{
test: /\.(jpg|png|gif|bmp|jepg)$/,
use: {
loader: 'url-loader',
options: {
limit: 0,
name: 'common/[name].[hash:6].[ext]', //图片重新命名避免冲突
publicPath: !isProduction ? '/' : 'oss的地址', // 如果是生产环境则替换成oss的地址
}
}
}
接下来只要我们在代码中使用这个plugin,打包的时候图片就会自动上传到oss,并且删除dist包中的全部图片啦