Jest: Cannot use import statement outside a module - import

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?

As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.

I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs

Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.

I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows

Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

Related

Getting this error with the #metaplex-foundation/js-next SDK

Currently working on a react app and I'm getting this error after installing metaplex.
My react-scripts version is 4.0.3
./node_modules/#metaplex-foundation/js-next/dist/esm/programs/token/gpaBuilders/TokenGpaBuilder.mjs
Can't import the named export 'ACCOUNT_SIZE' from non EcmaScript module (only default export is available)
I found out the solution in the git of metaplex here. I will leave you here the whole answer anyway.
Getting Started with Metaplex and CRA 5
This example sets up a new React app with Metaplex using "Create React App" (CRA) version 5 — i.e. using Webpack 5.
This example has been generated using the following steps:
Create a new project using the "Create React App" command.
npx create-react-app getting-started-react-cra5
cd getting-started-react-cra5
Install the Metaplex and the Solana SDKs.
npm install #metaplex-foundation/js #solana/web3.js
Install some polyfills.
npm install assert util crypto-browserify stream-browserify
Install and use react-app-rewired.
# Installs react-app-rewired.
npm install react-app-rewired
# Replaces "react-scripts" with "react-app-rewired" in package.json scripts.
sed -i '' 's/react-scripts /react-app-rewired /g' package.json
Override Webpack 5 configurations.
Create a new file to override Webpack 5 configurations.
touch config-overrides.js
Copy the following code inside the new config-overrides.js file.
const webpack = require("webpack");
module.exports = function override(webpackConfig) {
// Disable resolving ESM paths as fully specified.
// See: https://github.com/webpack/webpack/issues/11467#issuecomment-691873586
webpackConfig.module.rules.push({
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
});
// Ignore source map warnings from node_modules.
// See: https://github.com/facebook/create-react-app/pull/11752
webpackConfig.ignoreWarnings = [/Failed to parse source map/];
// Polyfill Buffer.
webpackConfig.plugins.push(
new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] })
);
// Polyfill other modules.
webpackConfig.resolve.fallback = {
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
assert: require.resolve("assert"),
fs: false,
process: false,
path: false,
zlib: false,
};
return webpackConfig;
};
Update your browser requirements.
Update the browserslist object of your package.json to include the following production requirements.
"browserslist": {
"production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
+ "chrome >= 67",
+ "edge >= 79",
+ "firefox >= 68",
+ "opera >= 54",
+ "safari >= 14"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
That's it!
You should not use #metaplex-foundation/js-next SDK, the actual repo is #metaplex-foundation/js, the name was changed and the updated repo is this, so try using #metaplex-foundation/js instead

How to correctly bundle a vscode extension using webpack

The problem that i am having is that when i run vsce package i still get the This extension consists of 3587 separate files. For performance reasons, you should bundle your extension: warning, i followed the Bundling Extension steps, debugging works as expected.
package.json
{
"main": "./out/extension",
"scripts": {
"vscode:prepublish": "webpack --mode production",
"webpack": "webpack --mode development",
"webpack-dev": "webpack --mode development --watch",
"compile": "npm run webpack",
"watch": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install"
},
}
The webpack config is an exact copy of the Bundling Extension example.
This sounds like you might've forgotten to add the source directories to .vscodeignore, so they're still being packaged into the release. The ignore file should probably contain at least the following, plus anything else not needed at runtime:
src/**
node_modules/**
If you are working with a Language Server extension which has both client and server folders, If you exclude the node_modules of the client and server from the bundle the extension would fail when installed and launch for the first time
.vscodeignore contains
.vscode
**/*.ts
**/*.map
out/**
node_modules/**
test_files/**
client/src/**
server/src/**
tsconfig.json
webpack.config.js
.gitignore
Also the documentation is a bit obsolete regarding the webpack.config.js, you have to wrap the 'use strict' into a function with all the settings.
The entry setting was changed according to my needs
//#ts-check
(function () {
'use strict';
const path = require('path');
/**#type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
entry: './client/src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
clean: true, //clean the dist folder for each time webpack is run
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]'
},
devtool: 'source-map',
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/
},
resolve: {
// support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
}
]
}
};
module.exports = config;
}());

TYPO3 CMS 8.7.27: Call to a member function getPackagePath() on null

After installing extensions in typo3 CMS 8.7.27, I got following error.. Seems like the ExtensionManagementUtility can't load the ah_contentapi.
This is my composer.json file in root (/var/www/html/typo3) for loading my extensions:
{
"repositories":[
{
"type":"composer",
"url":"https://composer.typo3.org/"
},
{
"type":"package",
"package":{
"name":"Bm/ah-content-api",
"version":"0.0.1",
"type":"typo3-cms-extension",
"source":{
"url":"https://user#bitbucket.org/company/ah_config_typo3.git",
"type":"git",
"reference":"master"
}
}
},
{
"type":"package",
"package":{
"name":"Bm/ah-contentelements",
"version":"0.0.1",
"type":"typo3-cms-extension",
"source":{
"url":"https://user#bitbucket.org/company/ah_contentelements_typo3.git",
"type":"git",
"reference":"master"
}
}
}
],
"name":"typo3/cms-base-distribution",
"description":"TYPO3 CMS Base Distribution",
"license":"GPL-2.0-or-later",
"require":{
"helhum/typo3-console":"^4.9.3 || ^5.2",
"typo3/cms-about":"^8.7.10",
"typo3/cms-belog":"^8.7.10",
"typo3/cms-beuser":"^8.7.10",
"typo3/cms-context-help":"^8.7.10",
"typo3/cms-documentation":"^8.7.10",
"typo3/cms-felogin":"^8.7.10",
"typo3/cms-fluid-styled-content":"^8.7.10",
"typo3/cms-form":"^8.7.10",
"typo3/cms-func":"^8.7.10",
"typo3/cms-impexp":"^8.7.10",
"typo3/cms-info":"^8.7.10",
"typo3/cms-info-pagetsconfig":"^8.7.10",
"typo3/cms-rte-ckeditor":"^8.7.10",
"typo3/cms-setup":"^8.7.10",
"typo3/cms-sys-note":"^8.7.10",
"typo3/cms-t3editor":"^8.7.10",
"typo3/cms-tstemplate":"^8.7.10",
"typo3/cms-viewpage":"^8.7.10",
"typo3/cms-wizard-crpages":"^8.7.10",
"typo3/cms-wizard-sortpages":"^8.7.10",
"typo3/cms":"^8.7",
"dmitryd/typo3-realurl":"2.*",
"GridElementsTeam/Gridelements":"8.2.*",
"clickstorm/cs_seo":"3.*",
"Bm/ah-content-api":"0.0.1",
"Bm/ah-contentelements":"0.0.1"
},
"scripts":{
"typo3-cms-scripts":[
"typo3cms install:fixfolderstructure",
"typo3cms install:generatepackagestates"
],
"post-autoload-dump":[
"#typo3-cms-scripts"
]
},
"extra":{
"typo3/cms":{
"web-dir":"public"
},
"helhum/typo3-console":{
"comment":"This option is not needed ay more for helhum/typo3-console 5.x",
"install-extension-dummy":false
}
},
"autoload":{
"psr-4":{
"Bm\\AhContentelements\\":"public/typo3conf/ext/ah_contentelements/Classes",
"Bm\\AhContentapi\\":"public/typo3conf/ext/ah_content_api/Classes"
}
}
}
I already cleared cache in install tool at:
1. -> important actions -> clear all cache
2. -> clean up -> Clean typo3temp/ folder
piece from composer.lock:
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is #generated automatically"
],
"content-hash": "954afd2318d54ec9b1dd0e4d7f9b445b",
"packages": [
{
"name": "Bm/ah-content-api",
"version": "0.0.1",
"source": {
"type": "git",
"url": "https://stevenhippovibe#bitbucket.org/hippovibe/ah_config_typo3.git",
"reference": "master"
},
"type": "typo3-cms-extension"
},
{
"name": "Bm/ah-contentelements",
"version": "0.0.1",
"source": {
"type": "git",
"url": "https://stevenhippovibe#bitbucket.org/stevenhippovibe/ah_contentelements_typo3.git",
"reference": "master"
},
"type": "typo3-cms-extension"
},
The Error occurs when the extension folder name under typo3conf/ext/<folder_name> doesn't match extension key used in some places of the system (e.g. using EXT:your_extension_key/... syntax in TypoScript).
Changing folder name fixed similar problem for me.
Check the PHP version and try to change it from i.e. 7.4 to 7.3.
I once had this problem with an extension that should be compatible with PHP 7.4, but wasn't in real life. This solved the problem for me.
Question here is:
How did you update to 8.7.27 (which composer command was executed)
How does your composer.lock look like?
Do you use TYPO3 console or any other special composer plugins / CLI commands to e.g. generate PackageStates.php?
I just ran into the same error message under TYPO3 9.5.5.
Solution:
Deinstall one TYPO3 extension after the other and try it out again. This will lead you to the extension which has an error. Most probably the error is inside of the file ext_localconf.php or ext_tables.php .
I got this error detail:
PHP Warning: Use of undefined constant FH_DEBUG_EXT - assumed 'FH_DEBUG_EXT' (this will throw an Error in a future version of PHP) in /var/www/html/global-extensions/ext/div2007/ext_localconf.php line 15
This has nothing to do with your error. But it can be that you have an error in one of your installed extensions or even in a backup of an extension, e.g. a folder named as extensionname.bak .
Also these recommendations can help:
https://wiki.typo3.org/Exception/CMS/1476107295

Babel 7 and babel-polyfill

After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "#babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '#babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?
.babelrc.js
const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins
if (nodeEnv === 'test'){
presetEnvConfig = {targets: {node: 'current'}}
plugins = ['istanbul']
} else {
presetEnvConfig = {
targets: {
browsers: ['last 2 versions', 'ie >= 11']
},
modules: false
}
plugins = ['react-hot-loader/babel']
}
const config = {
presets: [
['#babel/preset-env', presetEnvConfig],
'#babel/react',
'#babel/stage-2'
],
plugins,
}
types.js
import keyMirror from '../../../utils/keyMirror'
export default keyMirror({
Unassign: null,
Reassign: null,
QuickAssignment: null,
}, 'TagAssignmentTypes')
index.js
<Assignment
assignee={assignee}
tagId={tagId && tagId.toString(16)}
assignmentType={assignmentTypes.Reassign}
onRequestClose={() => this.setState({isAssignmentInProgress: false})}
onChange={onChange}
/>
#babel/polyfill is a wrapper package which only includes imports of stable core-js features (in Babel 6 it also included proposals) and regenerator-runtime/runtime, needed by transpiled generators and async functions. This package doesn't make it possible to provide a smooth migration path from core-js#2 to core-js#3: for this reason, it was decided to deprecate #babel/polyfill in favor of separate inclusion of required parts of core-js and regenerator-runtime.
Instead of
import "#babel/polyfill";
you should use those 2 lines:
import "core-js/stable";
import "regenerator-runtime/runtime";
Don't forget install those dependencies directly!
npm i --save core-js regenerator-runtime
Change
#babel/stage-2 to #babel/preset-stage-2
The following worked for me, add
**.babelrc**
{
"presets": [
["#babel/env"]
]
}
**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";
*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime

Ionic with ui-router.stateHelper

Is it possiable to use ionic with ui-router.stateHelper
I want to use this for help me working with nested views:
the property children is what I'm looking for.
If its not possible, how can i do something similar, without defining each child state with name: parent.child?
after installing and import im getting the next error:
TypeError: Cannot read property '#' of undefined at updateView (http://localhost:8100/lib/ionic/js/ionic.bundle.js:62199:69)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:62194:9
at invokeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21830:9)
at nodeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21330:11)
at compositeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20721:13)
at compositeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20725:13)
at compositeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20725:13)
at publicLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20596:30)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:14815:27
at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:29026:28) <ion-nav-view class="view-container" nav-view-transition="ios">
Ok This is working.. I had problem with the indjection.
this is the right way: (im using browserify)
npm install angular-ui-router.statehelper
then in the package.json
under browser:
"angular-ui-router-helper": "./node_modules/angular-ui-router.statehelper/statehelper.min.js"
and under browserify-shim
"browserify-shim": {
"angular": "angular",
"ionic": "ionic",
"angular-ui-router-helper": {
"exports": "angular.module('ui.router.stateHelper')"
}
},
and then in the index.js:
var rootModule = angular.module('AppName', ['ionic',require('angular-ui-router-helper').name]);
Then u can inject the stateHelperProvider to the config method :)