一个简化的Webpack插件示例,用于自动上传sourceMap文件到服务器
这个插件会在每次编译后寻找sourceMap文件,并将其上传到指定的服务器。这个例子假设服务器支持HTTPS,并且上传是通过POST请求实现的。根据实际情况,可能需要调整上传逻辑。
const fs = require('fs');
const path = require('path');
const https = require('https');
class AutoUploadSourceMapPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.afterEmit.tapAsync('AutoUploadSourceMapPlugin', (compilation, callback) => {
const assetNames = Object.keys(compilation.assets);
const sourceMapAssetName = assetNames.find((name) => /\.map$/.test(name));
if (!sourceMapAssetName) {
callback();
return;
}
const sourceMapPath = path.join(compilation.options.output.path, sourceMapAssetName);
const sourceMapContent = fs.readFileSync(sourceMapPath, 'utf-8');
const uploadOptions = {
hostname: this.options.hostname,
port: this.options.port,
path: this.options.path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': sourceMapContent.length
}
};
const req = https.request(uploadOptions, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
console.error(`Upload failed with status code: ${res.statusCode}`);
} else {
console.log('SourceMap uploaded successfully');
}
callback();
});
req.on('error', (e) => {
console.error(`Upload error: ${e.message}`);
callback();
});
req.write(sourceMapContent);
req.end();
});
}
}
module.exports = AutoUploadSourceMapPlugin;
使用这个插件的方法是在webpack配置文件中如下配置:
const AutoUploadSourceMapPlugin = require('./AutoUploadSourceMapPlugin');
module.exports = {
// ... 其他webpack配置
plugins: [
new AutoUploadSourceMapPlugin({
hostname: 'your-server.com',
port: 443,
path: '/path/to/upload/sourceMap'
})
]
};