使用:输入文件夹路径数组
const path = require("path"); function resolve(dir) { return path.join(__dirname, "..", dir); } //demo plugins: [ new AliasDirReplacementPlugin([resolve('www'),resolve('src')]),
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const fs = require("fs"); function findFileIndex(filepath,aliasDirs,extensions) { const resource=filepath.replace(/\?.+/,'') //是否存在后缀 let hasExt=-1; for(let i=0;i<extensions.length;i++){ if(resource.indexOf(extensions[i])+extensions[i].length===resource.length){ hasExt=i; break; } } //找到匹配得 let index=-1; for(let i=0;i<aliasDirs.length;i++){ const dirPath=aliasDirs[i]; if(resource.indexOf(dirPath)===0){ index=i break; } } const resourceArr=[] for(let i=0;i<aliasDirs.length;i++){ const dirPath=aliasDirs[i]; if(index===i){ resourceArr.push(resource) }else{ resourceArr.push(resource.replace(aliasDirs[index],dirPath)) } } let nIndex=-1; for(let i=0;i<resourceArr.length;i++){ const nResource=resourceArr[i]; if(fs.existsSync(nResource)){ nIndex=i; break; } if(hasExt===-1){ let fit=false; for(let j=0;j<extensions.length;j++){ if(fs.existsSync(nResource+extensions[j])){ fit=true break; } } if(fit){ nIndex=i; break; } } } return [index,nIndex] } /*别名文件夹替换插件 用于马甲包开发 * */ class AliasDirReplacementPlugin { constructor(aliasDirs) { this.aliasDirs=aliasDirs; } apply(compiler) { const aliasDirs = this.aliasDirs; const extensions=compiler.options.resolve.extensions const alias=compiler.options.resolve.alias compiler.hooks.normalModuleFactory.tap( "AliasDirReplacementPlugin", nmf => { nmf.hooks.beforeResolve.tap("AliasDirReplacementPlugin", result => { if (!result) return; if(/node_modules/.test(result.context)||/node_modules/.test(result.request)){ return result; } const request=result.request.replace(/\?.+/,''); let isAlias='' //解析别名 for(let key in alias){ if(result.request.indexOf(key)===0){ isAlias=key; break; } } //如果是别名解析 if(isAlias){ const filepath=result.request.replace(isAlias,alias[isAlias]); const [index,nIndex]=findFileIndex(filepath,aliasDirs,extensions) if(nIndex>-1){ result.request=filepath.replace(aliasDirs[index],aliasDirs[nIndex]); } return result; } if(/^(\.\/|\.\.\/)/.test(request)){ const [index,nIndex]=findFileIndex(path.join(result.context,request),aliasDirs,extensions) if(nIndex!==index){ result.context=result.context.replace(aliasDirs[index],aliasDirs[nIndex]); } } return result; }); } ); } } module.exports = AliasDirReplacementPlugin;