通过webpack loader 转移文件并重建路径

202 阅读1分钟

批量copy并重建文件路径

cppy-loader.js 自定义loader

var { getOptions } = require('loader-utils');
var chalk = require('chalk')
var process = require('child_process');
var copyfn = require('./copy.js')
module.exports = function loader(source) {
    var callback = this.async();    
    process.exec("echo '"+this.resourcePath + "' >> files.txt",function(err){
    }) 
    var resourcePath = this.resourcePath
    const options = getOptions(this)
    const {fromRoot,toRoot} = options
    var tarPath = resourcePath.replace(fromRoot, toRoot)
    copyfn(
        resourcePath,
        tarPath,
        source,
        function (err, result, sourceMaps, ast) {
            callback(err,source, sourceMaps, ast);
        },
    )
};

copy.js 重建路径并拷贝

const fs  = require('fs');
var process = require('child_process');
function writePathFile(resourcePath,path, codes,cb) {
    createDirsSync(path, function () {
        fs.copyFile(resourcePath, path, function (value) {
            process.exec("echo '"+path + "' >> success.txt",function(err){
                cb && cb()
            }) 
        },function(err){
            process.exec("echo '"+path + "' >> fail.txt",function(err){
                cb && cb()
            }) 
        });
    })
}
function createDirsSync(dir, callback) {
    var dirs = dir.split('/');
    if (!dirs[0] || dirs[0] == '.' || dirs[0] == "..") {
        dirs[1] = dirs[0] + "/" + dirs[1];
        dirs.shift();
    }
    if (dirs[dirs.length - 1] == "") {
        dirs.pop();
    }
    var len = dirs.length;
    var i = 0;
    var url = dirs[i];
    function mkDirs(url) {
        if (fs.existsSync(url)) {
            i = i + 1;
            if (len > i + 1) {
                url = url + "/" + dirs[i];
                mkDirs(url);
            }else{
                callback();
            }
        } else {
            fs.mkdirSync(url);
            mkDirs(url);
            // mkDir(url)
        }
    }
    mkDirs(url);
}
module.exports = writePathFile 

webpack使用loader

      {
        test: /\.*$/,
        use:{
          loader:path.resolve(__dirname, './loader/copy-loader.js'),
          options:{
            fromRoot:'[fromPath]',
            toRoot:'[destPath]'
          }
        },
        exclude: /node_modules/,
      },