I'm trying to use imported object to setup some restrictions for globals inside .eslintrc.js file, but import doesnt work. How can i make dynamic eslint config?
import {loadedGlobals} from '@/util/globals'
module.exports = {
'globals': Object.keys(loadedGlobals).reduce((acum, key) => {
acum[key] = false
return acum
}, acum),
// ...
}
I'm trying to use imported object to setup some restrictions for globals inside .eslintrc.js file, but import doesnt work. How can i make dynamic eslint config?
import {loadedGlobals} from '@/util/globals'
module.exports = {
'globals': Object.keys(loadedGlobals).reduce((acum, key) => {
acum[key] = false
return acum
}, acum),
// ...
}
Share
Improve this question
asked May 20, 2019 at 18:27
KaroliusKarolius
5811 gold badge7 silver badges12 bronze badges
2 Answers
Reset to default 7Update:
With the new configuration system you can use an eslint.config.js
file with "type": "module"
in your package.json to support import
statements.
Additionally, if you need to load an ESM module from a CJS context, the configuration file can export a promise, so you can run await import
inside an async
function.
async function config () {
const dep = await import('esm-dep')
return [dep]
}
module.exports = config()
The ability to export a promise is currently supported, just not documented yet. The updated docs have been merged, just not published yet.
There is also the hidden gem of the -c eslint.config.mjs
approach for node versions that support module system context via file extensions.
Original:
How to use import inside eslintrc file?
ESLint currently doesn't support a configuration file by the name of eslintrc
so I'm going to assume you mean .eslintrc.js
.
ESLint currently does not support ES Modules as you can see from the JavaScript (ESM) bullet item on their configuration file formats documentation.
If you are willing to install another dependency here is how you can use import
inside of .eslintrc.js
:
- Install the
esm
module,npm i esm -D
(Here I'm choosing as adevDependency
). - Create a new file as a sibling to
.eslintrc.js
called.eslintrc.esm.js
. - Inside of
.eslintrc.esm.js
include your ESLint configuration. Here you can useimport
and you should export your configuration asexport default { // Your config }
. - Inside
.eslintrc.js
include the following code:
const _require = require('esm')(module)
module.exports = _require('./.eslintrc.esm').default
Now you should be able to run eslint
as usual. A bit clunky with the extra file, but you can organize them in a directory if you like and use the --config
option of eslint
to point to the new location.
You might notice that you are using the old syntax when exporting your object. You could try using require()
instead of import.
Alternatively, you could look into Shareable Configs.