Creating React components with tsdx
To build a packageable React component, you need to build the code different that what Create React App does normally. For that purpose you need a bundler with a custom build step.
I've used rollup to create react components in the past. But while that approach worked in the past, I couldn't make it work with css modules
But then I discovered tsdx
Usage with create-react-app #
To add it to my current application, just install the package:
npm install --dev tsdx
And then add a build script:
package.json
:
"component:build": "tsdx build --entry src/MyComponent/index.tsx",
Of course, you can still using npm run start
to view your app.
Add css-modules #
If you want css modules support, you need install postcss rollup plugin:
npm i --dev rollup-plugin-postcss
And then create a tsdx configuration file:
tsdx.config.js
:
const postcss = require("rollup-plugin-postcss");
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
modules: {
globalModulePaths: [/src\/styles\/global/],
},
})
);
return config;
},
};
With that configuration styles in src/styles/global/*.css
will not be treated as css modules (remember create-react-app css modules must end with *.module.css
suffix)
Start from scratch #
tsdx comes with a init script:
npx tsdx create my-project
It has several templates, with a handy react with storybook: