【问题标题】:Transition from gulp to npm从 gulp 过渡到 npm
【发布时间】:2019-09-27 06:49:25
【问题描述】:

我正在尝试摆脱 gulp 并使用 npm 脚本。我们的开发人员使用不同版本的 node/gulp,而对插件和弃用的依赖一直是不必要的麻烦。

我正在尝试将我们的 gulp 脚本转换为 npm,但有一些地方我卡住了。我在从 gulp-sourcemaps 转换为 npm map-stream 以及从 gulp-uglify 转换为 uglifyjs 时遇到问题。

这是我们当前使用的 gulp 文件:

/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var pump = require('pump');
var del = require('del');

// set a variable telling us if we're building in release
var isRelease = true;
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'Release') {
    isRelease = false;
}

var config = {
    //Include all js files but exclude any min.js files
    src: ['Scripts/*.js', '!Scripts/*.min.js']
}

//delete the output file(s)
gulp.task('clean', function () {
    //del is an async function and not a gulp plugin (just standard nodejs)
    //It returns a promise, so make sure you return that from this task function
    //  so gulp knows when the delete is complete
    return del(['Scripts/*.min.js', 'Scripts/Maps/*.map']);
});

 // Combine and minify all files from the app folder
// This tasks depends on the clean task which means gulp will ensure that the 
// Clean task is completed before running the scripts task.
gulp.task('scripts', ['clean'], function (cb) {

    pump([
      gulp.src(config.src),
      sourcemaps.init(),
      uglify({ mangle: isRelease }),
      rename({ suffix: '.min' }),
      sourcemaps.write('Maps', { includeContent: false, sourceRoot: './' }),
      gulp.dest('Scripts/')
    ],
    cb
    );
});

//Set a default tasks
gulp.task('default', ['scripts'], function () { });

这是我当前的 npm 脚本(仍有一些错误):

 /*
This is the main entry point for defiinng npm tasks
*/

const del = require('del');
var map = require('map-stream');
var pump = require('pump');
var vfs = require('vinyl-fs');
var uglifyjs = require('uglify-js');

// set a variable telling us if we're building in release
var isRelease = true;
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'Release') {
    isRelease = false;
}
console.log(process.env.NODE_ENV);

//task to delete output files
(async () => {
    const deletedPaths = await del(['Scripts/*.min.js', 'Scripts/Maps/*.map']);

    console.log('Deleted files and folders:\n', deletedPaths.join('\n'));
})();




var log = function(file, cb) {
    console.log(file.path);
    cb(null, file);
  };

//    vinyl metadata object
//   Include all js files but exclude any min.js files

  pump([
    vfs.src(['Scripts/*.js', '!Scripts/*.min.js']),
    map(log),
    uglifyjs({mangle:isRelease}),
    rename({ suffix: '.min' }),

    (vfs.dest('Scripts/'))

 ])

映射应该在 Scripts 目录下创建一个 Maps 文件夹。

 Scripts
     --Maps
           --jquery.min.js.map
           --jquery-1.4.1.min.js.map

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: npm gulp npm-scripts gulp-sourcemaps


    【解决方案1】:
    /*
     *   This is the main entry point for defining npm tasks
     *   Author: *****
     *   Date: 06/03/2019
    */
    
    const del = require('del');
    var Uglify = require("uglify-js"),
        fs = require('fs'),
        async = require('async'),
        path = require('path'),
       rename = require('rename'),
       parentDir = 'Scripts';
    

    检查构建类型(发布、生产、调试等)是使用节点完成的,因此在这部分脚本中不需要进行任何更改。

    // set a variable telling us if we're building in release
    var isRelease = true;
    if (process.env.NODE_ENV && process.env.NODE_ENV !== 'release') {
       isRelease = false;
    }
     console.log(process.env.NODE_ENV);
    

    至于 npm del 模块,我选择了同步方式。原因是我希望单独处理每个文件而不是并行处理。 async 方法一直缺少 .acingore 文件,而且没有多少文件需要删除。

    //  Returns an array of deleted paths
    const deletedPaths = del.sync(['Scripts/*.min.js', 'Scripts/Maps/*.map', 'Scripts/.acignore']);
    
    console.log('Deleted files and folders:\n', deletedPaths.join('\n'));
    

    这个块做所有的工作。这个函数连续运行一个函数数组,每个函数将它们的结果传递给数组中的下一个。每个函数在完成时都会传递一个回调。

    async.waterfall([
    function (cb) {
        fs.readdir(parentDir, cb);
    },
    function (files, cb) {
        // files is just an array of file names, not full path
        console.log('Files being looped through:\n');
        // run 10 files in parallel
        async.eachLimit(files, 10, function (filename, done) {
            var filePath = path.join(parentDir, filename);
    
            var sourceFile = filename;
    
            if (!fs.lstatSync(filePath).isDirectory()) {
    
                // create a .temp file to be minified
                fs.copyFileSync(filePath, filePath + '.temp', (err) => {
                    if (err) throw err;
                    // console.log(filePath + ' was copied to ' + filePath + '.temp');
                });
                //  path the .temp file
                var tempfilePath = path.join(parentDir, filename + '.temp');
                //  console.log('tempfilePath: ' + tempfilePath);
    
                //  check for /Maps directory, if not, create it
                var mapsDir = parentDir + '/Maps';
                try {
                    if (!fs.existsSync(mapsDir)) {
                        fs.mkdirSync(mapsDir)
                    }
                } catch (err) {
                    console.error(err)
                }
    
                //  rename file to add .min suffix for minified files
                filename = rename(filename, { suffix: '.min' });
                //  console.log('filename after rename\n' + filename + '\n');
                var newfilePath = path.join(parentDir, filename);
                //   console.log('filePath after rename\n' + newfilePath + '\n');
    
                //  Synchronous rename
                fs.renameSync(tempfilePath, newfilePath);
    
                //  get contents of sourceFile 
                //  The source file must be interpolated with [] in order
                //  to be mapped correctly, otherwise your map will get the content
                //  of the source file but not have a link back to the source
                try {
                    var code = {
                        [sourceFile]: fs.readFileSync(filePath, 'utf-8')
                    };
                    console.log(code);
                } catch (e) {
                    console.log('Error:', e.stack);
                }
    
                //  minify file 
                // the syntax for uglifyjs minify is minify(code, options)
                // therefore you need the contents of the file in order to minify it
                // and source map it
                var uglyCode = Uglify.minify(code,
                    {
                        mangle: isRelease,
                        sourceMap: {
                            includeSources: false,
                            filename: '../' + filename,
                            root: '../',
                            url: 'Maps/' + filename,
                        },
                    }
    
                );
    
                //  console.log('Source file: ' + sourceFile);
    
                //  write minified file to directory
                fs.writeFile(newfilePath, uglyCode.code, function (err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(filename + " has been mangled");
                    }
                }
                );
    
                //  write map file to directory
                fs.writeFile(mapsDir + '/' + filename + '.map', uglyCode.map, function (err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(filename + '.map' + " has been mapped");
                    }
                }
                );
                done();
            }
        }, cb);
    }
    ], function (err) {
    err && console.trace(err);
    
    console.log('\nNo more files in path\n');
    });
    

    旁注:如果您运行的是 node 10+,并且无法在 .csproj 文件中设置 npm 的路径,请全局安装 node,您不需要设置路径。

    希望我在代码中的 cmets 就足够了。如果你想摆脱 gulp 并过渡到 npm,祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2019-03-03
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多