The Situation
I have a NodeJS project that uses Babel and ESLint (6.8).
I'm using the relatively new syntax for aggregate exports (export * as name1 from …;).
The Code
constants.js
export const x = 5
export const y = 6
index.js
export * as constants from './constants'
sandbox.js
import { constants } from './index'
console.log(constants.x)
When I run babel-node sandbox.js everything works just fine, and the value for x (5) is rendered.
.eslintrc
{
"extends": "airbnb-base",
"parser": "babel-eslint",
"env": {
"es6": true,
"node": true,
"jest": true
}
}
.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "13.10"
}
}
]
],
"plugins": [
"#babel/plugin-proposal-export-namespace-from"
]
}
The Problem
ESLint seems to be confused by my aggregate export, rendering the following error when I lint:
sandbox.js
1:10 error constants not found in './index' import/named
The Question
How do I get ESLint to recognize that the named aggregate does in fact exist? I would like to be able to still benefit from the import/named checks overall.
Related
First of all, some facts:
Node.js requires that all local imports include the imported module's extension (e.g. import hello from './hello.js', not import hello from './hello').
TypeScript will compile imports with or without the .js extension, which means a missing .js extension is a runtime error.
TypeScript doesn't transform imports to add the .js extension or convert .ts to .js.
In my Node.js project, I want to make missing a missing .js extension be a build-time error using the import/extensions ESLint rule. However, when I enable this rule using the following configuration:
{
"root": true,
"env": {
"node": true
},
"parser": "#typescript-eslint/parser",
"plugins": [
"#typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:#typescript-eslint/eslint-recommended",
"plugin:#typescript-eslint/recommended"
],
"settings": {
"import/resolver": {
"typescript": {},
"node": {
"extensions": [".js"]
}
}
},
"rules": {
"import/extensions": ["error", "ignorePackages"]
}
}
running eslint gives me the following error:
/sandbox/src/index.ts
1:19 error Missing file extension "ts" for "./hello.js" import/extensions
Source files:
// index.ts
import hello from "./hello.js";
hello();
// hello.ts
export default function hello() {
console.log("Hello");
}
CodeSandbox link: https://codesandbox.io/s/elated-germain-13glp7
I fixed this with the following config:
{
"root": true,
"env": {
"node": true
},
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:#typescript-eslint/eslint-recommended",
"plugin:#typescript-eslint/recommended"
],
"rules": {
"import/extensions": ["error", "ignorePackages"],
"import/no-unresolved": "off"
}
}
The main thing is to disable the "import/no-unresolved" rule and remove "settings"."import/resolver"."node". ("import/no-unresolved" is redundant as unresolved imports are resolved at the compilation stage.) Other items removed here were already being added as a result of extending the #typescript-eslint plugins.
I found an eslint plugin that can fix missing .js extensions for imports in .ts files, instead of just showing an error:
https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts
https://www.npmjs.com/package/eslint-plugin-file-extension-in-import-ts
Install:
npm i -D eslint-plugin-file-extension-in-import-ts
Add to .eslintrc file:
{
"plugins": [
"file-extension-in-import-ts"
],
"rules": {
"file-extension-in-import-ts/file-extension-in-import-ts": "error"
}
}
NOTE: I ran into an issue similar to https://github.com/import-js/eslint-plugin-import/issues/1292 when using this package, and it will incorrectly try to add .js extensions on these paths when fixing automatically.
You could try ts-add-js-extension package to append .js extension to the transpiled JavaScript files. After you install you can do
ts-add-js-extension add --dir={your-transpiled-outdir}
I'm struggeling now for a couple of days to get my testsetup running. Rough outline: Vite, Svelte (with ts), Jest.
I'm using import.meta.env.SOMENAME for my environment vars although this works fine for development as soon as a component uses import.meta.env the test will fail with:
SyntaxError: Cannot use 'import.meta' outside a module
I've tried different transformers, babel-plugins and configs but never succeeded...
My jest config:
"jest": {
"globals": {
"ts-jest": {
"isolatedModules": true
}
},
"verbose": true,
"transform": {
"^.+\\.svelte$": [
"svelte-jester",
{
"preprocess": true
}
],
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": "babel-jest"
},
"setupFilesAfterEnv": ["<rootDir>/setupTests.ts"],
"moduleFileExtensions": ["js", "ts", "svelte"]
}
babel.config.js
module.exports = {
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current"
}
}
]
]
};
svelte.config.cjs
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
emitCss: true,
preprocess: sveltePreprocess()
};
Among other things I tried to use #babel/plugin-syntax-import-meta but ended up with the same error. Also vite-jest looked very promising but again I couldn't make it work.
I appreciate every hint I can get. If I can provide any additional info please let me know. Also my knowledge of vite and babel is very limited so REALLY appreciate any help IU can get on this topic.
Update (Solution)
So If you use babel you could use babel-preset-vite. The approach with esbuild-jest from Apu is also good solution that many people use. Unfortunately those things didn't work for me so I decided to use a workaround with vite's define.
This workaround consists of two steps.
replace import.meta.env with process.env (if this is a deal breaker for you then I hope you have luck with the solutions above) You only have to replace the instances in files you want to test with jest.
Update Vite config with define. This step is necessary or your build will break (dev will still work)
vite.config.js
const dotEnvConfig = dotenv.config();
export default defineConfig({
define: {
"process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
"process.env.VITE_APP_SOMENAME": `"${process.env.VITE_APP_SOMENAME}"`
},
...
)};
I know this is just a workaround but maybe this helps someone. Thanks & Good Luck.
A more recent alternative to Jest that understands import.meta.env is Vitest.
It should require almost no additional configuration to get started and it's highly compatible with Jest so it requires few changes to the actual tests.
The advantages of Vitest over Jest for this use case are:
It's designed specifically for Vite and will process tests on demand
It will reuse your existing Vite configuration:
Any define variables will be replaced as expected
Extensions that Vite adds to import.meta will be available as usual
I was having issues with svelte component testing as well using jest. babel is not good at resolving import.meta. I used esbuild-jest to transform both ts and js files. It solves the issue with the import.meta. Here is my jest.config.cjs.
npm i esbuild esbuild-jest -D
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
const config = {
"transform": {
"^.+\\.svelte$": [
"svelte-jester",
{
"preprocess": true
}
],
"^.+\\.(ts|tsx|js|jsx)$": ["esbuild-jest"]
},
"moduleFileExtensions": [
"js",
"ts",
"tsx",
"svelte"
],
"setupFilesAfterEnv": [
"#testing-library/jest-dom/extend-expect"
],
"collectCoverageFrom": [
"**/*.(t|j)s",
"**/*.svelte"
],
coverageProvider: 'v8',
"coverageDirectory": "./coverage",
"coveragePathIgnorePatterns": [
"/node_modules/",
"/.svelte-kit/"
],
"moduleNameMapper": pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
module.exports = config;
I want to include the rule no-unpublished-import from eslint-plugin-node, however, it is conflicting with my current .eslintrc because I am using typescript-eslint and eslint-import-resolver-typescript.
It is my current configuration:
{
"parser": "#typescript-eslint/parser", // Specifies the ESLint parser
"extends": [
"airbnb-base",
"plugin:#typescript-eslint/recommended", // Uses the recommended rules from the #typescript-eslint/eslint-plugin
"prettier", // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array
"prettier/#typescript-eslint" // Uses eslint-config-prettier to disable ESLint rules from #typescript-eslint/eslint-plugin that would conflict with prettier
],
"parserOptions": {
"project": "./tsconfig.json",
"ecmaVersion": 6, // Allows for the parsing of modern ECMAScript features
"sourceType": "module" // Allows for the use of imports
},
"rules": {
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".ts"]
},
// use <root>/tsconfig.json
"typescript": {
"alwaysTryTypes": true // always try to resolve types under `<root>#types` directory even it doesn't contain any source code, like `#types/unist`
}
}
},
"root": true
}
The code compiles correctly, however, if I add to the extends option the plugin:node/recommended the compilation process will fail:
1:1 error Import and export declarations are not supported yet node/no-unsupported-features/es-syntax
1:43 error "express" is not found node/no-missing-import
2:1 error Import and export declarations are not supported yet node/no-unsupported-features/es-syntax
My package.json includes the node": ">=12.0.0. Also, this rule should be ignored because I am using typescript. On the other hand, I am just exporting types from express because the module don't use it.
According to this issue the conflict should be resolved by eslint-plugin-node.
How can I accomplish the merge of both plugins? Do I have to go disabling rules one by one?
UPDATED:
It seems it was asked in this issue on the eslint-plugin-node repository. It works for no-unsupported-features and no-missing-import, however, it is still failing with the import definition of express with no-extraneous-import.
UPDATED 2:
It seems eslint-plugin-node is working on a enhancement to accomplish it. Issue here
Firstly, you have to add the option tryExtension to include TS files:
"settings": {
"node": {
"tryExtensions": [".js", ".json", ".node", ".ts", ".d.ts"]
},
To solve the no-unsupported-features/es-syntax, according to this issue about adding information to works with TypeScript, if you work with transpilers you will have to ignore it under rules:
"node/no-unsupported-features/es-syntax": ["error", { "ignores": ["modules"] }],
On the other hand, use just types and not the code is not supported yet by the eslint-plugin-node. They are working on a enhancement to solve it. However,, to solve the no-missing-import, you have to add to the resolvePath the node_modules/#types:
"node": {
"resolvePaths": ["node_modules/#types"],
"tryExtensions": [".js", ".json", ".node", ".ts", ".d.ts"]
},
Even so, it will generate a no-extraneous-import because it doesn't detect the module, because it is just a type. Meanwhile they are working on this enhancement, you can use allowModules under that rule for workaround:
"node/no-extraneous-import": ["error", {
"allowModules": ["express"]
}]
It's been a while since I started a nodejs project from scratch, so was a bit of a headscratcher to set up and configure eslint, babel etc.
right now my babelrc is :
{
"presets": [
[
"env",
{
"targets": {
"node": "10"
}
}
]
],
"plugins": [
[
"transform-runtime",
{
"regenerator": true
}
]
]
}
package.json has dev dependencies:
"babel-cli": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
Now I want to loop over a list of objects. For each, I need to perform some asynchronous tasks that I'll need to await on, so I did:
for await (const thing of things) {
const foo = await doSomethingThatTakesAwhile(thing)
// etc
}
but when I run it in dev (nodemon via babel-node) now there's a syntax error on the await:
for await (const thing of things) {
^
Syntax Error Unexpected token, expected (
at Parser.pp$5.raise (... \node_modules\babylon\lib\index.js:4454:13)
at Parser.pp.unexpected (... \node_modules\babylon\lib\index.js:1761:8)
at Parser.pp.expect (... \node_modules\babylon\lib\index.js:1749:33)
at Parser.pp$1.parseForStatement (... \node_modules\babylon\lib\index.js:2008:8)
etc..
Do I have to change my babel config, and/or have I completely misunderstood for/await and await/async ?
I found another project in which i know for await of works... it looks like I'm using old babel plugins and not the new, separated out #babel/xxx libs. After trial and error installing and uninstalling stuff: this is the resulting babelrc that worked:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "10"
}
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
},
"#babel/preset-env"
]
]
}
By this point I had installed all of:
#babel/core
#babel/node
#babel/cli
#babel/preset-env
#babel/plugin-transform-runtime
Then I ran into this issue: https://github.com/meteor/meteor/issues/10128
So Had to also install #babel/runtime pegged at 7.0.0-beta.55 ... and now it builds!!
I believe you need the babel-plugin-proposal-async-generator-functions plugin to use the for await of syntax.
I have the following .babelrc.js in the root folder:
{
"plugins": [
"#babel/plugin-transform-flow-strip-types",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-strict-mode",
"#babel/plugin-transform-runtime"
],
"cache": "true"
}
but when it tries to run node ./packages/jest-cli/bin/jest.js I see:
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
for various types of caching, using the first param of their handler functions:
What am I missing?
Use new babel.config.js
https://new.babeljs.io/docs/en/next/babelconfigjs.html
module.exports = function(api) {
api.cache(true)
return {
plugins: [
"#babel/plugin-transform-flow-strip-types",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-strict-mode",
"#babel/plugin-transform-runtime"
]
}
}