Skip to content

Shyp/babel-plugin-import-noop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 

Repository files navigation

babel-plugin-import-noop

A babel plugin to turn certain types of import statements into noops that declare empty objects.

Why?

If you're using CSS Modules via a build tool like Webpack's css-loader, then when you build your app bundle webpack will magically transform imports like:

import style from './some-style.scss';

— into JavaScript that injects this style into your pages.

However, if you want to run tests, you'll hit a syntax error if you try to run the JavaScript files as-is, since the CSS they're importing isn't valid JavaScript. You could compile an entire "test bundle" with webpack before running the tests, but that adds a substantial boot time to every run. Instead, you can use the babel require hook, and use this plugin to replace all instances of:

import style from './some-style.scss';

with

const style = {};

— during compilation.

Usage

$ npm install --save-dev babel-plugin-import-noop

Then, in your .babelrc:

{
  "plugins": ["import-noop"]
}

Or, to only load this plugin during tests (i.e. not in your actual bundle):

{
  "env": {
    "test": {
      "plugins": ["import-noop"]
    }
  }
}
NODE_ENV=test mocha ....

To specify a list of file extensions which should be transformed, you can add additional options to the plugin declaration:

{
  "plugins": [
    ["import-noop", {
      "extensions": ["scss", "css"]
    }]
  ]
}

It doesn't work!

If you've installed or updated this plugin and you're still seeing syntax errors thrown, there's a chance Babel is caching the old parse tree. The variables used to control this are documented here.

Unless you've overwritten any settings, you can clear this cache via:

$ rm ~/.babel.json

Limitations

Since the newly defined object won't have any properties, anything you're reading from it in your code (e.g. style.className) will resolve to undefined. A pull request to allow defining properties using the plugin configuration would be very useful!

License

MIT

About

A Babel plugin to transform certain types of `import` statements into noops

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors