Created
September 30, 2022 19:57
-
-
Save darknoon/293494e2356b0027873e6018b1479fa1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-var-requires */ | |
const { ReplaceSource } = require("webpack-sources") | |
/// This is a workaround for a bug in Figma plugins where they don't like the text "import(" | |
class FigmaWorkaroundPlugin { | |
// based on BannerPlugin https://github.com/webpack/webpack/blob/05ebf5bba670152101d1cc0f42f165b9fd295164/lib/BannerPlugin.js | |
process(file) { | |
if (file.source().includes("import(")) { | |
const replace = new ReplaceSource(file, "fix import( in Figma plugins FigmaWorkaroundPlugin") | |
for (const match of file.source().matchAll(/import\(/g)) { | |
const start = match.index | |
const end = start + match[0].length | |
replace.replace(start, end, "import_") | |
} | |
return replace | |
} else { | |
return file | |
} | |
} | |
apply(compiler) { | |
const cache = new WeakMap() | |
compiler.hooks.compilation.tap("FigmaWorkaroundPlugin", (compilation) => { | |
// for webpack 5, this would be processAssets I think | |
compilation.hooks.optimizeChunkAssets.tap( | |
{ | |
name: "FigmaWorkaroundPlugin", | |
stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONS, | |
}, | |
() => { | |
for (const chunk of compilation.chunks) { | |
for (const file of chunk.files) { | |
if (file.endsWith(".js")) { | |
compilation.updateAsset(file, (old) => { | |
const safe = cache.get(old) ?? this.process(old) | |
cache.set(old, safe) | |
return safe | |
}) | |
} | |
} | |
} | |
} | |
) | |
}) | |
} | |
} | |
module.exports = FigmaWorkaroundPlugin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment