Skip to content

Conversation

Copy link

Copilot AI commented Nov 12, 2025

Found and eliminated two major code duplication patterns in the webpack plugin implementation.

Changes

Extract common loader insertion logic (src/plugin.ts)

  • Created createLoaderAdder() factory function to replace two nearly identical addLoader() implementations in addStyleLoader and addSanLoader
  • Parameterized differences: target loader matching, insertion position (before/after/start), rule normalization, and duplicate tracking
  • Eliminated ~25 lines of duplicated webpack rule manipulation logic

Before:

// In addStyleLoader - ~40 lines
function addLoader(rule: RuleSetRule) {
  if (addedRules.has(rule)) return;
  addedRules.add(rule);
  if (rule.oneOf) { /* ... */ }
  if (rule.use) {
    // Find css-loader and insert after it
    const ruleIndex = rule.use.findIndex(/* ... */);
    rule.use.splice(ruleIndex, 0, loaderPath);
  }
}

// In addSanLoader - ~30 lines, nearly identical
function addLoader(rule: RuleSetRule) {
  if (rule.oneOf) { /* ... */ }
  if (rule.loader) { /* normalize to rule.use */ }
  if (rule.use) {
    // Insert at start
    rule.use.unshift(loaderPath);
  }
}

After:

const addLoader = createLoaderAdder('style-loader', {
  findTargetLoader: 'css-loader',
  insertPosition: 'before',
  addedRulesSet: addedRules
});

const addLoader = createLoaderAdder('san-loader', {
  insertPosition: 'start',
  normalizeLoader: true
});

Extract CSS locals code generation (src/lib/callSanSsr.ts)

  • Created generateLocalsCode() helper to replace duplicated object serialization logic for default and named module styles
  • Eliminated ~16 lines of identical code for building data['$style'] and data['$moduleName'] assignments

Before:

if (Object.keys(locals).length > 0) {
  code += '        data[\'$style\'] = {\n';
  code += `            ${Object.keys(locals).map(item =>
    `${JSON.stringify(item)}: ${JSON.stringify(locals[item])}`
  ).join(',')}\n`;
  code += '        };\n';
}
// ... same pattern repeated for namedModuleCss

After:

code += generateLocalsCode('$style', locals);
namedModuleCss.forEach(({name, locals}) => {
  if (locals) code += generateLocalsCode(`$${name}`, locals);
});
Original prompt

Find and refactor duplicated code


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI changed the title [WIP] Refactor duplicated code for improved maintainability Refactor duplicated loader insertion and CSS locals generation logic Nov 12, 2025
Copilot AI requested a review from meixg November 12, 2025 06:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants