You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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-js can'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.src to preserve original file metadata
    • Configured uglify-js to generate sourcemaps with correct filenames and URLs
    • Used vinyl-sourcemaps-apply to attach sourcemaps to vinyl files
    • Directed vfs.dest to output sourcemaps to the Scripts/Maps directory
  • File Renaming: Manually updated the vinyl file's basename to add the .min suffix (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:dev for development mode (no mangling)
  • Run npm run build:prod for release mode (with mangling)
  • Check Scripts for your .min.js files and Scripts/Maps for the corresponding .map files—this matches your desired directory structure perfectly!

内容的提问来源于stack exchange,提问作者Stacker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:31:01