vue,react項目中使用webpack打包中直接打包成壓縮包的方法


這里以react項目為例,(vue項目類似)

為改造的 pageage.json 中 scripts 位置的代碼

 

  "scripts": {
    "start": "node scripts/start.js",
    "build": "node --max_old_space_size=4096 scripts/build.js",
    "build:test": "node --max_old_space_size=4096 scripts/build.test.js",
    "test": "node scripts/test.js"
  },

注:node --max_old_space_size=4096 這里代碼與本次介紹無關,詳見  https://www.cnblogs.com/taohuaya/p/13444470.html

這里的兩個命令  yarn build  和  yarn build:test 分別是打包 正式包 和 測試包

會在項目的根目錄生 build文件 和 build.test 文件夾

 

 

 

我們的 目標是 運行上面兩個命令時 分別能 自動壓縮 build文件夾下的文件和 build.test文件夾下的文件為 build.zip 和 build.test.zip,后期我們上線發包的時候直接 拷貝出去 這兩個 zip文件即可。

 

在項目中找個合適的位置 新建一個 zip.js 

 

 

在編寫 zip.js 之前我們得先下載兩個工具包分別是 

archiver  用來壓縮文件 詳見:https://www.archiverjs.com/
minimist  用來解析 node 命令行傳來的參數 詳見:http://nodejs.cn/learn/nodejs-accept-arguments-from-the-command-line

yarn add archiver minimist --dev
//
npm i archiver minimist --save-dev
 
        

 scripts/zip.js

// require modules
const argv = require('minimist')(process.argv.slice(2)); // 用來獲取命令行傳來的參數
var fs = require('fs');
var archiver = require('archiver');
var path = require('path');

/* 打包環境用來區分 正式包還是測試包 */
const isProduction = argv['build_env'] === 'production';
console.log('打包環境為:', argv['build_env']);
console.log('文件壓縮中...');
// 創建一個文件來流  數據, 即將文件壓縮得到的文件地址。
// var output = fs.createWriteStream(__dirname + '/build:test.zip');
var output = fs.createWriteStream( path.resolve(__dirname, isProduction ? '../build.zip' : '../build.test.zip') );
var archive = archiver('zip', {
    zlib: { level: 9 } // 設置壓縮級別.
});

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function() {
    // console.log('壓縮包地址為:', path.resolve(__dirname, '../build.test','build.test.zip'));
    console.log('壓縮包地址為:', path.resolve(__dirname, isProduction ? '../build/build.zip': '../build.test/build.test.zip'));
    console.log('壓縮包大小', archive.pointer() + ' total bytes');
    console.log('壓縮程序已經完成,輸出文件描述符已經關閉/archiver has been finalized and the output file descriptor has closed.');
    // 利用 fs.rename 重命名api 移動文件
});

// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function() {
    console.log('數據流已流完 / Data has been drained');
});

// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function(err) {
    if (err.code === 'ENOENT') {
        // log warning
        console.warn('stat故障和其他非阻塞錯誤');
    } else {
        // throw error
        throw err;
    }
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
    console.error('壓縮文件出錯');
    throw err;
});

archive.on('finish', function (err){
    if(err) throw err;
/*
    var sourceFile = path.resolve(__dirname, '../build.test.zip');
    var destPath = path.resolve(__dirname, '../build.test', 'build.test.zip');
*/
    var sourceFile = path.resolve(__dirname, isProduction ? '../build.zip' : '../build.test.zip');
    var destPath = path.resolve(__dirname, isProduction ? '../build/build.zip' : '../build.test/build.test.zip');
    
    
    fs.rename(sourceFile, destPath, function (err){
        if(err) throw err;
        console.log('壓縮包文件移動成功');
    });
    // 移動文件
    console.log('壓縮包文件移動中...');
});

// pipe archive data to the file
// 通過管道將數據歸檔到壓縮文件
archive.pipe(output);

/*
// append a file from stream
var file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });

// append a file from string
archive.append('string cheese!', { name: 'file2.txt' });

// append a file from buffer
var buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });

// append a file
archive.file('file1.txt', { name: 'file4.txt' });

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');
*/

// append files from a sub-directory, putting its contents at the root of archive
// 從子目錄追加文件,將其內容放在歸檔(壓縮文件)的根目錄中
/*
directory(dirpath, destpath, data)  目錄路徑, 存檔(壓縮文件)中的目標路徑(false代表放到根目錄), 要壓縮的數據
*/
// archive.directory('build:test/', false);
// var fileDirPath = path.resolve(__dirname, '../build.test');
var fileDirPath = path.resolve(__dirname, isProduction ? '../build' : '../build.test');
archive.directory(fileDirPath, false);
/*
// append files from a glob pattern
archive.glob('subdir/!*.txt');
*/

// 壓縮文件
// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
archive.finalize();
View Code

修改 package.json 中script部分

  "scripts": {
    "start": "node scripts/start.js",
    "build": "node --max_old_space_size=4096 scripts/build.js && node scripts/zip.js --build_env=production",
    "build:test": "node --max_old_space_size=4096 scripts/build.test.js && node scripts/zip.js --build_env=test",
    "test": "node scripts/test.js"
  },

在原來的基礎上新增 紅色內容部分

&& 符號表示 等運行完畢 上一段js 后 在運行 下一段 

即 當 運行

命令  node --max_old_space_size=4096 scripts/build.js 結束后

運行  node scripts/zip.js --build_env=production 命令

詳見: 。。。。

 

通過以上處理后 我們就可以得到相應的壓縮包了

 

通用運行命令

yarn build 或 yarn build:test 

此時 build.zip 和 build.test.zip 就是我們向要的東西了

完成


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM