Created
October 20, 2021 03:09
-
-
Save hyrious/4fcc3680e7f9998377c7eab42487791a to your computer and use it in GitHub Desktop.
esbuild plugin styled-components
This file contains 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
import babel from '@babel/core' | |
import styled from 'babel-plugin-styled-components' | |
import fs from 'node:fs' | |
export default { | |
name: "styled-components", | |
setup({ onLoad }) { | |
const root = process.cwd(); | |
onLoad({ filter: /\.[tj]sx$/ }, async (args) => { | |
let code = await fs.promises.readFile(args.path, "utf8"); | |
let plugins = [ | |
"importMeta", | |
"topLevelAwait", | |
"classProperties", | |
"classPrivateProperties", | |
"classPrivateMethods", | |
"jsx" | |
]; | |
let loader = "jsx"; | |
if (args.path.endsWith(".tsx")) { | |
plugins.push("typescript"); | |
loader = "tsx"; | |
} | |
const result = await babel.transformAsync(code, { | |
babelrc: false, | |
configFile: false, | |
ast: false, | |
root, | |
filename: args.path, | |
parserOpts: { | |
sourceType: "module", | |
allowAwaitOutsideFunction: true, | |
plugins | |
}, | |
generatorOpts: { | |
decoratorsBeforeExport: true | |
}, | |
plugins: [ | |
styled | |
], | |
sourceMaps: true, | |
inputSourceMap: false | |
}); | |
return { contents: result.code + `//# sourceMappingURL=data:application/json;base64,` + Buffer.from(JSON.stringify(result.map)).toString("base64"), loader }; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For what? Use babel for compiling tsx files?