Skip to content

Instantly share code, notes, and snippets.

@darknoon
Created September 30, 2022 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darknoon/293494e2356b0027873e6018b1479fa1 to your computer and use it in GitHub Desktop.
Save darknoon/293494e2356b0027873e6018b1479fa1 to your computer and use it in GitHub Desktop.
/* 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