Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created October 20, 2021 03:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyrious/4fcc3680e7f9998377c7eab42487791a to your computer and use it in GitHub Desktop.
Save hyrious/4fcc3680e7f9998377c7eab42487791a to your computer and use it in GitHub Desktop.
esbuild plugin styled-components
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 };
});
}
}
@polRk
Copy link

polRk commented Oct 28, 2022

For what? Use babel for compiling tsx files?

@Y-developer
Copy link

I created this as an npm package.
esbuild-plugin-styled-components

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment