从Gulp迁移至npm脚本:sourcemap与uglify转换问题求助
Migrating from Gulp to npm Scripts: Fixing Sourcemap & Minification Issues
Let's fix your npm script step by step to replicate the exact functionality of your original Gulp task. First, let's break down the key issues in your current script:
uglify-jscan't plug directly into streams, so we need to process each file individually- Sourcemap generation and output wasn't properly configured
- The clean task runs asynchronously but wasn't coordinated with the minification workflow
- File renaming logic wasn't integrated correctly into the stream
Step 1: Install Missing Dependency
First, add vinyl-sourcemaps-apply to your dev dependencies—it helps attach sourcemaps generated by uglify-js to vinyl file objects:
npm install vinyl-sourcemaps-apply --save-dev
Step 2: Corrected npm Script (save as scripts.js)
const del = require('del'); const map = require('map-stream'); const pump = require('pump'); const vfs = require('vinyl-fs'); const uglifyjs = require('uglify-js'); const sourcemapsApply = require('vinyl-sourcemaps-apply'); const path = require('path'); // Determine if we're in release mode const isRelease = process.env.NODE_ENV === 'Release'; console.log(`Building in ${isRelease ? 'Release' : 'Development'} mode`); // Clean task: Delete old minified files and sourcemaps async function clean() { const deletedPaths = await del(['Scripts/*.min.js', 'Scripts/Maps/*.map']); console.log('Deleted files and folders:\n', deletedPaths.join('\n')); } // Minification task: Process each JS file, generate minified version and sourcemap async function processScripts() { return new Promise((resolve, reject) => { pump([ // Enable sourcemap tracking for input files vfs.src(['Scripts/*.js', '!Scripts/*.min.js'], { sourcemaps: true }), map((file, cb) => { if (file.isBuffer()) { // Read original file content const originalCode = file.contents.toString('utf8'); // Configure uglify-js with sourcemap settings const uglifyOptions = { mangle: isRelease, sourceMap: { filename: path.basename(file.path), url: `${path.basename(file.path, '.js')}.min.js.map`, includeSources: true } }; // Minify code and generate sourcemap const result = uglifyjs.minify(originalCode, uglifyOptions); if (result.error) { return cb(result.error); } // Update file content to minified code file.contents = Buffer.from(result.code); // Rename file to add .min suffix file.basename = `${path.basename(file.basename, '.js')}.min.js`; // Attach generated sourcemap to the vinyl file sourcemapsApply(file, result.map); } cb(null, file); }), // Write minified files to Scripts/, sourcemaps to Scripts/Maps/ vfs.dest('Scripts/', { sourcemaps: { path: './Maps' } }) ], (err) => { if (err) { console.error('Error processing scripts:', err); reject(err); } else { console.log('Scripts processed successfully!'); resolve(); } }); }); } // Run tasks in sequence: Clean first, then process scripts async function main() { await clean(); await processScripts(); } main().catch(err => console.error('Build failed:', err));
Step 3: Add npm Script to package.json
Update your package.json to include easy-to-run commands:
{ "scripts": { "build": "node scripts.js", "build:dev": "NODE_ENV=Development node scripts.js", "build:prod": "NODE_ENV=Release node scripts.js" } }
Key Changes Explained
- Task Coordination: We wrapped clean and processing logic in async functions to ensure cleanup finishes before minification starts—no more race conditions!
- Sourcemap Handling:
- Enabled sourcemap tracking in
vfs.srcto preserve original file metadata - Configured
uglify-jsto generate sourcemaps with correct filenames and URLs - Used
vinyl-sourcemaps-applyto attach sourcemaps to vinyl files - Directed
vfs.destto output sourcemaps to theScripts/Mapsdirectory
- Enabled sourcemap tracking in
- File Renaming: Manually updated the vinyl file's
basenameto add the.minsuffix (no extra rename package required) - Error Handling: Added proper error catching in the stream and main workflow to log issues clearly
Testing the Script
- Run
npm run build:devfor development mode (no mangling) - Run
npm run build:prodfor release mode (with mangling) - Check
Scriptsfor your.min.jsfiles andScripts/Mapsfor the corresponding.mapfiles—this matches your desired directory structure perfectly!
内容的提问来源于stack exchange,提问作者Stacker
相关产品推荐
相关产品推荐

