ES6 import/export not working with babel-jest - javascript

I have installed both babel and babel-jest for use within my project. I have configured my babel.config.js file as so:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
However I get the following error when trying to run my tests
import * as formObj from '../../../../public/Forms/Classes/Form.class.js';
^
SyntaxError: Unexpected token *
My package.json looks like this for babel, node, and babel-jest
"devDependencies": {
"#babel/preset-env": "^7.9.6",
"babel-jest": "^26.0.1",
"jest": "^24.9.0"
},
"engines": {
"node": ">=11.0.0"
}
Looking online- it seems like a lot of people who have issues with import/export in jest have issues due to their babel.config.js (or lack thereof). However- I made mine exactly how it is like in the jest docs. The error itself seems to step from a babel issue- but I'm failing to see where it could be.
I have tried various other things such as having a translation property in my jest config file, or trying different formats of importing my file, but nothing seems to work correctly.
Any advice greatly appreciated for solving this error.

Related

karma-typescript confused by .d.ts typings into failing to bind to npm package code

I'm importing an npm package into my project with a package.json like this:
{
// ...
"browser": "dist/umd/index.js",
"main": "dist/cjs/index.js",
"module": "dist/fesm2015/index.mjs",
"esm2015": "dist/index.js",
"fesm2015": "dist/fesm2015/index.mjs",
"typings": "dist/index",
"sideEffects": false,
"exports": {
"node": {
"module": "./dist/fesm2015/index.mjs",
"require": "./dist/cjs/index.js"
},
"browser": {
"module": "./dist/fesm2015/index.mjs",
"default": "./dist/umd/index.js"
},
"default": "./dist/cjs/index.js"
},
// ...
}
(I really, really wanted to have "type": "module" in the above package, but that creates a whole other world of pain trying to make karma and other tools happy.)
I can build and run my project that uses the above npm package just fine, and I can run mocha unit tests outside of karma without any problem. However, when running under karma, I get errors like this:
20 06 2021 10:58:05.127:INFO [Chrome 91.0.4472.106 (Mac OS 10.15.7)]: Connected on socket 9qHeabxqGGw_tCrRAAAB with id 99567255
Chrome 91.0.4472.106 (Mac OS 10.15.7) #tubular/util should blend colors correctly FAILED
TypeError: math_1.round is not a function
at colorFromRGB (src/browser-graphics-util.js:2:2895)
at Object.blendColors (src/browser-graphics-util.js:2:1803)
at Context.<anonymous> (src/index.spec.js:60:45)
Chrome 91.0.4472.106 (Mac OS 10.15.7): Executed 30 of 30 (1 FAILED) (0.818 secs / 0.789 secs)
TOTAL: 1 FAILED, 29 SUCCESS
It seems that my project code isn't correctly binding to the code in the imported npm package, and all tests that depend on code from that package fail.
If I perform a little manual surgery on the contents of my node_modules directory, and modify the package.json of the imported npm package by removing "typings": "dist/index", karma is once again happy, and all my tests succeed.
Why, why for deity-of-your-choice's sake, does the existence of typings make any difference to karma-typescript about the success or failure of binding to the code in the npm package?
I definitely want that package (which is a package I created in another project) to provide TypeScript typings, so permanently getting rid of typings is NOT an option. How do I tell karma or karma-typescript to either ignore these typings, or simply not get so confused by them?
Here is my current karma.conf.js:
module.exports = function (config) {
config.set({
frameworks: ['chai', 'karma-typescript', 'mocha'],
files: [
'src/**/*.ts'
],
preprocessors: {
'src/**/*.ts': 'karma-typescript'
},
reporters: ['progress', 'karma-typescript'],
browsers: ['Chrome'],
karmaTypescriptConfig: {
tsconfig: './tsconfig.karma.json'
},
});
};
And tsconfig.karma.json, which simply exists to make karma build CommonJS modules instead of ESM modules:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"target": "ES2015"
},
"exclude": [
"dist",
"node_modules"
]
}
UPDATE:
Another bit of information on this problem. If I use an explicit import like this:
import { max, min, round } from '../node_modules/#tubular/math/dist/cjs';
...instead of:
import { max, min, round } from '#tubular/math';
...the problem goes away, which confirms that this is a module resolution problem.
So what is it about module resolution that's changed while running in karma with karma-typescript? Are there settings I can use to tweak module resolution?
I figured it out.
karma-typescript is dependent on browser-resolve, and my imported package.json had a "browser" entry, but meant for a somewhat different purpose, and clearly not at all compatible with how karma-typescript uses browser-resolve.
As long as I take out my "browser" field, the "typings" field can stay, and no longer causes my tests to fail.

Eslint wont work because of eslint plugin error?

I can't seem to get my eslint to work.
I have the eslint extenstion on vscode. I created a new node project and npm installed eslint as a dev dependency. I chose the Air-BNB style and then went to check if it worked. Whenever I open a file I get a notification saying there is an error with eslint.
Vscode notification error message
ESlint stack trace error output
Some things I did:
I installed eslint locally.
At one point I found out that I had eslint installed globally so I
removed it and stuck with the local install per project basis.
Ive disabled and enabled vscode eslint (Extension ESlint 2.1.8).
My Config File:
module.exports = {
env: {
browser: true,
commonjs: true,
es2020: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 11,
},
rules: {
},
};
Here are my dev dependencies:
"devDependencies": {
"eslint": "^7.7.0",
"eslint-config-airbnb-base": "^14.2.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-require": "0.0.1"
}
The problem is right their in the error message, you have two different versions of eslint-plugin-import in your node-modules tree. You just need to make sure you only have one version.
I expect you tried to add a newer version than the one used by CRA.

How can I publish an NPM module with both commonjs and es6 versions?

I have a module I want to publish to npm. I have found some "solutions" that are 4+ years old, examples using babel 5.x, and other problems that made the examples not work as shown.
Ideally I want to write my code using es6 and build/transpile with babel such that it can be imported with require() in scripts or import in modules.
Right now, here's my (sample) module that shows what I've tried.
// index.js
export default function speak () {
console.log("Hello, World!");
}
// .babelrc
{
"comments":false,
"presets": [
["#babel/env", {"modules": "commonjs"}]
],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
"add-module-exports"
]
}
// package.json
{
"name": "foo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.10.5",
"#babel/core": "^7.10.5",
"#babel/plugin-transform-modules-commonjs": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"babel-plugin-add-module-exports": "^1.0.2"
}
}
And, finally, a demo script (demo.js)
// demo.js
const speak = require('./dist/index.js');
speak();
When I do npm run build and then node demo.js, it works as expected:
Hello, World!
I would also like to be able to have a module (add "type":"module" to package.json) and then use a demo.js file this way:
import speak from './dist/index.js';
speak();
However, I get this an error that a default export isn't available:
import speak from './dist/index.js';
^^^^^
SyntaxError: The requested module './dist/index.js' does not provide an export named 'default'
I don't really care what the answer is, I'd just like to know what the best practices are. Should I just export as ES6? Should I just require commonjs? Is there a way of transpiling with two available targets?
Note:
node v14.5.0
npm v6.14.6
#babel/core v7.10.5
You can use a bundler like webpack or rollup in combination with babel. They provide options to compile to multiple targets. Normally any library code is compiled to below targets:
ESM or MJS (Ecmascript modules)
UMD (Universal Modules)
You can also compile to CJS (CommonJS module) or IIFE (Immediately invoked function expression).
UMD and ESM are pretty much standard these days (esp. UMD because it is combination of IIFE, CJS and AMD).
You can explore official documentation for Webpack or Rollup. However, I have created a tool which you can use to achieve the output you are looking for. https://www.npmjs.com/package/rollup-boilerplate
You can check it out, play around with it, hack it. I think it can be good starting point. You can checkout this article to get started: https://medium.com/#contactsachinsingh/setting-up-a-rollup-project-under-two-minutes-fc838be02d0e

Polyfills in Gatsby.js - String.prototype.matchAll

I'm having trouble polyfilling String.prototype.matchAll in Gatsby.js, which is using Webpack to bundle. Based on my understanding of the Gatsby Browser Support documentation, I thought that this should be done by default, since #babel/preset-env is used under the hood. After further investigation, it looks like the version of core-js that #babel/preset-env is using is 2. I tried to update the .babelrc file (shown below) to include separate configuration of the preset where I could update the version, but received errors. When trying to build with the new config, I received an error in every place there was an attempted polyfill (shown below).
{
"presets": [
[
"babel-preset-gatsby",
{
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
],
[
"#babel/preset-env",
{
"targets": {
"browsers": [">0.25%", "not dead"]
},
"corejs": "3.6"
}
]
]
}
ERROR #98123 WEBPACK
Generating JavaScript bundles failed
Can't resolve 'core-js/modules/web.dom-collections.iterator' in 'C:\Users\xxxx\OneDrive\Desktop\directory-frontend-gatsby\src\components'
ERROR #98123 WEBPACK
Generating JavaScript bundles failed
Can't resolve 'core-js/modules/web.dom-collections.for-each' 'C:\Users\xxxx\OneDrive\Desktop\directory-frontend-gatsby\src\components'
etc...
I should mention that I'm using the newest version of core-js, #babel/preset-env, and #babel/core.
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.5",
"core-js": "^3.6.4"
Also, I thought that it might have been an issue with running this on Windows, since paths are constructed using \ instead of /, but also attempted the build on Ubuntu and received the same output.
Any help would be appreciated.
Thanks.

Eslint - Maximum call stack size exceeded

Working in a React / Webpack project I started to have problems with the eslint library.
The eslint package is downloaded using npm and it's used to validate the project using a webpack preLoader.
preLoaders: [{
test: /\.jsx?$/,
loaders: [ 'eslint' ],
include: path.resolve(__dirname, 'app')
}]
It used to work fine until recently when I tried to git clone the same project to an other folder.
After installing the dependencies "npm install" and starting the project "npm start" the following error appeared.
ERROR in ./main.view.jsx
Module build failed: RangeError: Maximum call stack size exceeded
at keys (native)
at Referencer.Visitor.visitChildren (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:78:24)
at Referencer.Visitor.visit (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:112:14)
at Referencer.Visitor.visitChildren (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:93:26)
at Referencer.Visitor.visit (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:112:14)
at Referencer.Visitor.visitChildren (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:93:26)
at Referencer.Visitor.visit (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:112:14)
at Referencer.Visitor.visitChildren (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:88:38)
at Referencer.Visitor.visit (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:112:14)
at Referencer.Visitor.visitChildren (project/node_modules/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js:93:26)
# ./app.jsx 17:26-57
The strange part of all is that the old project installation still works.
The problem must be somewhere in the node_modules folder because when I copy the modules from the old installation to the new one the project suddenly works.
I did a "npm list --depth=0" on both projects and both have the same packages and versions. Why one is working and the other one not?
I guess the problem is in the eslint package because when I remove the preLoader it works again.
I'm really confused about that. Someone had that problem before?
My main.view.jsx looks like that
import React from 'react';
export default class MainView extends React.Component {
render() {
return (
<div />
);
}
}
Thanks!
I could solve the problem by myself.
Isolating everything I found out that the problem was the babel dependencies.
For some reason the combination of versions I had of babel-core, babel-loader and babel-eslint where not working properly together.
I changed the babel versions required for my project in the package.json and now everything works fine.
- "babel-core": "5.6.x",
- "babel-loader": "5.3.x",
- "babel-eslint": "3.1.x",
+ "babel-core": "5.8.x",
+ "babel-loader": "5.4.x",
+ "babel-eslint": "4.1.x",
Here my eslint dependencies
"eslint": "1.10.x",
"eslint-loader": "1.1.x",
"eslint-plugin-react": "3.10.x"
Hope the time I lost with that will help someone else!
Looking through the thread https://github.com/eslint/eslint/issues/4485, the solution now is very simply to update babel-eslint to 4.1.6. For instance, "babel-eslint": "^4.1.6". Now works :)
For some reason, I was able to fix this by just disabling a single rule:
Add this into your rules:
'no-octal-escape': 0,
if your code contains
export * from "."
remove above line

Categories