Ignore side-effect imports using babel plugin

Huey He
2 min readNov 30, 2020

When using React for server-side rendering, to reuse our code as much as possible, it’s pretty common to share component code between server-side and client-side. On the client-side, one of the most frequently used methods for styling your components is importing the CSS file as a side-effect, and extract the CSS code into a bundled CSS file using packing tools like webpack. Below is a simplified example.

// Button.jsx
import './style.css';
export function Button() { // your component with classNames }

However, when the code above is used in server-side rendering, the import statement is not only unnecessary but also troublesome. Nodejs can’t parse the imported CSS code correctly. So we need to find a way to ignore these side-effect imports while performing server-side rendering. Here comes the babel-plugin-transform-require-ignore. It’s very useful for use-cases similar to the example above.

The require-ignore plugin uses path extensions to identify paths that need to be ignored. It could cover most of the use-cases, but it couldn’t deal with imports nested inside a node module. Let’s say our component depends on a javascript file, which requires some sass files, within a node module.

// Button.jsx
import 'module/button/style';
export function Button() { // component code }// module/button/style.js
import './variable.scss';
import './mixins.scss';
import './button.scss';

Since babel won’t transform code inside node_modules , the code inside module/button/style is not parsed by the require-ignore plugin.

To solve this problem, we need to specify more than file extensions. So here is an alternative babel-plugin-transform-import-ignore I wrote to address this issue. It allows us to specify path patterns that we want to ignore. Here’s the example babel configuration file to fix the problem mentioned above.

{
"babel-plugin-transform-import-ignore",
{
"patterns": [
"module/*/style"
]
}
}

The plugin supports wildcard string literals and regular expressions (only available inside a javascript babel configuration file). Hope that it can help you out in some edge cases and feel free to contribute or report issues.

--

--