Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use export default in .eslintrc.js file instead of module.exports

I would like to use export default obj instead of module.exports = obj in my .eslintrc.js file, because everywhere else in the codebase we are using export.

So far no luck, it was difficult to search for this problem.

The error I get:

> eslint src

Cannot read config file: src/.eslintrc.js
Error: Unexpected token export
src/.eslintrc.js:23
export default foo;
^^^^^^

SyntaxError: Unexpected token export
like image 1000
Vince Varga Avatar asked Nov 08 '22 11:11

Vince Varga


1 Answers

To use the ES2015 syntax for default exports in an ESLint config file, one can use a combination of Babel for transpilation and Pirates for hooks to hijack a require statement that imports your ESLint config file written in ES2015. Allow me to explain.

Usually, ESLint will look for a .eslintrc.js file in the project root, and it usually is parsed by Node.js without Babel. We will be repurposing this file so that it does two things: registering a hook and importing the ES2015 ESLint config file.

Assuming you already have a .eslintrc.js using the ES2015 default export syntax, cut the contents out of that file and paste it into a new file named .es2015lintrc.js or similar. The name is irrelevant; it can be called anything you want.

// .es2015lintrc.js

export default {

// ESLint config properties...

}

Make sure you have the @babel/preset-env, @babel/core, eslint, and pirates packages installed before continuing. Next, create a file that defines your hook and its behavior. We'll call it hook.js for simplicity.

// hook.js

const {addHook} = require('pirates');
const {transform} = require('@babel/core');

module.exports = options =>
  addHook(
    function(source, filename) {
      return transform(source, {
        presets: [
          [
            '@babel/preset-env',
            {
              modules: 'cjs',
              targets: {
                node: process.versions.node
              }
            }
          ]
        ]
      }).code;
    },
    {
      exts: ['.js'],
      ignoreNodeModules: true,
      ...options
    }
  );

Then import this module into the original .eslintrc.js using a require statement and register the hook that hijacks and transforms all files imported with future require statements. Finally, the ESLint config file written in ES2015 syntax can be imported using our hijacked require statement.

// .eslintrc.js

const registerHook = require('./hook');
registerHook();

module.exports = require('./.es2015lintrc').default;

Now you should be good to go! One can use this same method when writing a Babel config in ES2015 syntax too. Enjoy!

like image 176
DerekNonGeneric Avatar answered Nov 14 '22 21:11

DerekNonGeneric