Problem
contents/amazon.tsx and contents/walmart.tsx contain nearly identical code:
- Same
getStyle implementation
- Same
getOverlayAnchor implementation
- Same App component structure
- Only differences are marketplace-specific config values
Solution
Create a factory function to generate content scripts:
// contents/createMarketplaceContent.ts
import type { PlasmoCSConfig, PlasmoGetOverlayAnchor, PlasmoGetStyle } from "plasmo"
import styleText from "data-text:~style.css"
import { BaseProductApp } from "~/components/BaseProductApp"
interface MarketplaceConfig {
matches: string[]
urlMatches: RegExp[]
getProductId: (url: string) => string | null
marketplace: string
}
export const createMarketplaceContent = (config: MarketplaceConfig) => {
return {
config: { matches: config.matches } as PlasmoCSConfig,
getStyle: (() => {
const style = document.createElement("style")
style.textContent = styleText
return style
}) as PlasmoGetStyle,
getOverlayAnchor: (() => document.body) as PlasmoGetOverlayAnchor,
App: () => (
<BaseProductApp
urlMatches={config.urlMatches}
getProductId={config.getProductId}
marketplace={config.marketplace}
/>
)
}
}
Then each marketplace file becomes:
// contents/amazon.tsx
import { createMarketplaceContent } from "./createMarketplaceContent"
const getAmazonProductId = (url: string): string | null => {
const dpMatch = url.match(/\/dp\/([A-Z0-9]+)/)
const gpMatch = url.match(/\/gp\/product\/([A-Z0-9]+)/)
return dpMatch?.[1] || gpMatch?.[1] || null
}
const { config, getStyle, getOverlayAnchor, App } = createMarketplaceContent({
matches: ["*://*.amazon.com/*"],
urlMatches: [/\/dp\/|\/gp\/product\//],
getProductId: getAmazonProductId,
marketplace: "amazon"
})
export { config, getStyle, getOverlayAnchor }
export default App
Impact
- Reduces duplicate code
- Makes adding new marketplaces easier
- Ensures consistency across marketplaces
Priority
High
Problem
contents/amazon.tsxandcontents/walmart.tsxcontain nearly identical code:getStyleimplementationgetOverlayAnchorimplementationSolution
Create a factory function to generate content scripts:
Then each marketplace file becomes:
Impact
Priority
High