1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| const {resolve} = require('path'); const {writeFileSync} = require('fs'); const utils = require('../utils');
class Simplepack { constructor(options) { this.options = options; this.resources = []; }
run() { (function getFileInfo(entry, upperLevel = '') { let path = entry; const cwd = process.cwd(); if (!path.includes(cwd)) { path = resolve(cwd, upperLevel, `${path.endsWith('.js') ? path : `${path}/index.js`}`); } if (!existsSync(path)) { throw new Error(`请检查目录,不存在 ${entry} 模块`); }
const fileInfo = this.compile(path); const { dependencies: fileDependencies } = fileInfo; if (fileDependencies.length > 0) { fileDependencies.forEach((item) => { getFileInfo.call(this, item, entry.substring(0, entry.lastIndexOf('/') + 1)); }); } fileInfo.filename = entry; this.resources.push(fileInfo); }.bind(this))(this.entry); this.emit(); }
compile(path) { const isRelative = /\.\/|\.\\/; if (isRelative.test(path)) { path = resolve(process.cwd(), path); } const ast = utils.getAST(path); return { dependencies: utils.getDependencies(ast), source: utils.getTransformFromAST(ast) } }
emitFile() { const {entry = '', output: {filename = '', path = ''}} = this.options; const outputPath = resolve(path, filename); const module = this.resources.map(item => `'${item.filename}': function(require, modules, exports) {${item.source}`).join(','); const bundle = `(function (module) { function require(filename) { var fn = module[filename]; var modules = {exports: {}}; fn(require, modules, modules.exports); return modules.exports; } require('${entry}'); })({${module}})`; writeFileSync(outputPath, bundle); } }
|