Skip to content

Commit

Permalink
feat: new plugin classes
Browse files Browse the repository at this point in the history
 - ModuleGenerator to gerate a module.js file with lazy loading
 - fileUploader to start in watch mode and upload changed files
  • Loading branch information
frankpagan committed Dec 28, 2023
1 parent 57c489d commit 7cf0898
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const fs = require('fs');
const upload = require('@cocreate/cli/src/commands/upload.js')

class ModuleGenerator {
constructor(modulesConfig) {
this.modulesConfig = modulesConfig;
}

apply(compiler) {
let CoCreateConfig;
if (typeof this.modulesConfig === 'object')
CoCreateConfig = this.modulesConfig.config;
else {
try {
CoCreateConfig = require(this.modulesConfig.configPath);
} catch (error) {
console.error('Error loading CoCreate.config.js:', error);
throw error; // Stop compilation process if configuration is critical
}
}
let modulesGenerated = false

compiler.hooks.beforeCompile.tapAsync('CoCreateLazyloader', (params, callback) => {
if (modulesGenerated)
callback();
else {
let outputPath = this.modulesConfig.outputPath || './modules.js'; // Default path for generated module.js

// Generate module content based on CoCreateConfig
let moduleContent = `import { dependency, lazyLoad } from '@cocreate/lazy-loader';\n\n`;
Object.entries(this.modulesConfig).forEach(([moduleName, moduleInfo]) => {
if (moduleName === 'outputPath' || typeof moduleInfo !== 'object') return;
if (moduleInfo.selector) {
// Generate lazyLoad statements for modules with selectors
moduleContent += `lazyLoad('${moduleName}', '${moduleInfo.selector}', () => import(/*webpackChunkName: "${moduleName}-chunk"*/ '${moduleInfo.import}'));\n`;
} else {
// Generate dependency statements for other modules
moduleContent += `dependency('${moduleName}', import(/*webpackChunkName: "${moduleName}-chunk"*/ '${moduleInfo.import}'));\n`;
}
});

// Write the module content to the specified outputPath
fs.writeFile(outputPath, moduleContent, (err) => {
if (err) {
console.error(`Error writing ${outputPath}:`, err);
callback(err); // Handle errors in async hook
} else {
modulesGenerated = true
console.log(`${outputPath} generated successfully.`);
callback(); // Proceed with compilation
}
});
}
});
}
}
class fileUploader {
constructor(env) {
this.env = env;
this.isWatching = false;
}

apply(compiler) {
if (this.env.beforeCompilation) {
// Directly perform upload here
upload(process.cwd(), ['../', '-w']);
}

if (this.env.afterCompilation) {
compiler.hooks.emit.tapAsync('watchFiles', (compilation, callback) => {
if (!this.isWatching) {
this.isWatching = true;
upload(process.cwd(), ['../', '-w']);
}
callback();
});
}
}
}


module.exports = { ModuleGenerator, fileUploader };

0 comments on commit 7cf0898

Please sign in to comment.