Webpack cannot find keymirror module with Typescript import - import

I'm using Typescript, React, and Webpack and struggling to import the keymirror module.
I am using the latest version of typescript.
package.json
{
"name": "Fun",
"version": "1.0.0",
"description": "Dear Webpack Gods, please help.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "",
"dependencies": {
"eventemitter3": "^1.1.1",
"flux": "^2.0.3",
"keymirror": "^0.1.1",
"react": "^0.13.3",
"ts-loader": "^0.5.0",
"typescript": "^1.6.0-dev.20150812"
},
"devDependencies": {
"css-loader": "^0.16.0",
"style-loader": "^0.12.3"
}
}
webpack.config.js
module.exports = {
entry: './App/app.tsx',
output: {
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.tsx', '.ts']
},
module: {
loaders: [
{ test: /\.ts(x?)$/, loader: 'ts-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"jsx": "react",
"sourceMap": true
},
"files": [
"./typings/tsd.d.ts",
"./App/app.tsx"
]
}
The offending import is located in ./User/Constants.ts
import keyMirror = require('keymirror');
export = keyMirror({
LOGIN_ATTEMPT: null
});
I have tried using the standalone npm module as seen above, as well as attempting to require it from react/lib/keyMirror.
Any ideas?
(EDIT: Yes, I know it's a 12 line module that I could just copy into my code.)
Solution from Basarat (with slight modification)
declare module 'keymirror' {
function keyMirror(obj: Object);
export = keyMirror;
}

import keyMirror = require('keymirror');
You need to tell typescript about it. Basically something like :
declare module 'keymirror' {
var export:any;
export = export;
}
In a file called global.d.ts.
Some docs : http://basarat.gitbooks.io/typescript/content/docs/types/ambient/intro.html

Related

Error: Jest: Got error running globalSetup ../#shelf/jest-mongodb/setup.js, reason: Instance Exited before being ready and without throwing an error

I'm following the documentation on jestjs.io. When I try to run a test I get this error:
Error: Jest: Got error running globalSetup - /home/.../node_modules/#shelf/jest-mongodb/setup.js, reason: Instance Exited before being ready and without throwing an error!
This happened both when I've used typescript and also when I created a simple app using javascript instead:
package.json:
{
"name": "mongojest",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"#shelf/jest-mongodb": "^3.0.1"
},
"scripts": {
"test": "jest"
},
"dependencies": {
"jest": "^28.1.0"
}
}
jest.config.js:
module.exports = {
coverageProvider: "v8",
"preset": "#shelf/jest-mongodb"
};
I haven't made any changes other than the minimum installs to get it running.
I got around this issue by installing Ubuntu 20.04. I was using the newer Ubuntu 22.04 and it seem to have caused some issues.
I installed typescript in my project. That was enough to run. Follow my configuration files
//package.json
{
"name": "research-with-programmers-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --passWithNoTests --silent --noStackTrace --runInBand",
"test:verbose": "jest --passWithNoTests --runInBand",
"test:unit": "yarn test -- --watch -c jest-unit-config.ts",
"test:integration": "yarn test -- --watch -c jest-integration-config.ts",
"test:staged": "yarn test -- --findRelatedTest",
"test:ci": "yarn test -- --coverage"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#shelf/jest-mongodb": "^4.1.0",
"#types/bcrypt": "^5.0.0",
"#types/jest": "^28.1.8",
"#types/mongodb": "^4.0.7",
"#types/node": "^18.7.13",
"#types/validator": "^13.7.6",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-standard-with-typescript": "^22.0.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",
"git-commit-msg-linter": "^4.1.3",
"husky": "^8.0.1",
"jest": "^29.0.1",
"lint-staged": "^13.0.3",
"ts-jest": "^28.0.8",
"ts-node": "^10.9.1",
"typescript": "^4.8.2"
},
"dependencies": {
"bcrypt": "^5.0.1",
"mongodb": "^4.10.0",
"validator": "^13.7.0"
}
}
//jest-config.ts
export default {
roots: ['<rootDir>/src'],
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/protocols/*.ts',
'!<rootDir>/src/**/*protocols.ts',
'!<rootDir>/src/**/models/*.ts',
'!<rootDir>/src/**/usecases/*.ts',
'!<rootDir>/src/**/index.ts'
],
collectCoverage: true,
coverageDirectory: 'coverage',
coverageProvider: 'v8',
testEnvironment: 'node',
preset: '#shelf/jest-mongodb',
transform: {
'.+\\.ts$': 'ts-jest'
}
}
// jest-mongodb-config.ts
export default {
mongodbMemoryServerOptions: {
instance: {
dbName: 'jest'
},
binary: {
version: '4.0.3',
skipMD5: true
},
autoStart: false
}
}

Set up testing-library/react with mocha got SyntaxError: Unexpected token

I am setting up testing-library/react with mocha. Faced a lot of problems on the setup that were resolved by installing babel libraries and configuring them in .babelrc file as explained on the bottom most part of this question. Now, I am stuck on this error:
> mocha --exit --require #babel/register --require jsdom-global/register
D:\projects\demo_app\node_modules\antd\es\row\index.js:1
(function (exports, require, module, __filename, __dirname) { import { Row } from '../grid';
^
SyntaxError: Unexpected token {
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
This comes from ant.design component which uses the syntax above. I have tried to test a dummy component like below:
const component = () => (<div>hello</div>)
And it has no problem. But whenever I import my real component that I need to test that is using ant design, I get the error above.
Is it setup part for babel not configured properly? I have no idea how to fix the error. Somehow have a guess that it might be related to babel presets or plugins.
P.S. My project is using Create React App, the exact same test runs smoothly with Jest, but for some reason I don't want to use jest.
Below is .babelrc
{
"presets": [
["#babel/preset-env",
{
"targets": {
"esmodules": true,
"node": "current"
}
}
],
["#babel/preset-react"]
],
"plugins": [
["#babel/plugin-proposal-class-properties"],
["module-resolver", {
"root": ["./src"],
"alias": {
"underscore": "lodash"
}
}]
]
}
Below is package.json
{
"dependencies": {
"antd": "^4.4.2",
"axios": "^0.19.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-google-oauth": "^1.0.0",
"react-icons": "^3.10.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.1",
"recompose": "^0.30.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"styled-components": "^5.0.1",
"validator": "^13.1.17"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "mocha --exit --require #babel/register --require jsdom-global/register",
"test:jest": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "7.12.9",
"#babel/plugin-proposal-class-properties": "7.12.1",
"#babel/preset-env": "^7.12.7",
"#babel/preset-react": "7.12.7",
"#babel/register": "7.12.1",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"babel-eslint": "10.1.0",
"babel-plugin-module-resolver": "^4.0.0",
"chai": "4.2.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint-plugin-flowtype": "^3.13.0",
"eslint-plugin-import": "^2.20.1",
"husky": "^4.2.1",
"jsdom": "^16.4.0",
"jsdom-global": "^3.0.2",
"mocha": "8.2.1",
"msw": "^0.19.5",
"react-test-renderer": "^16.13.1",
"redux-mock-store": "^1.5.4",
"standard": "^14.3.1"
},
"optionalDependencies": {
"fsevents": "^2.1.2"
},
"standard": {
"parser": "babel-eslint",
"ignore": [
"/public"
]
},
"jest": {
"transformIgnorePatterns": [
"node_modules/?!(react)/"
]
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
]
}
Any help would be appreciated.
You have "esmodules": true which forces Babel to use ES modules. That means that if you're using Node, it needs to support ES modules, and you either need to have your tests in .mjs files or have "type": "module" in package.json. If this isn't supported or you want to support older Node versions, remove "esmodules": true from your Babel config to enable compatibility with CJS modules.

Babel : As of v7.0.0-beta.55, we've removed Babel's Stage presets

I'm trying to create a build for this project but I've faced this issue with babel :
Error: [BABEL] D:\open-source\React\react-notify\src\components\Notification\Action\index.js:
As of v7.0.0-beta.55, we've removed Babel's Stage presets.
Please consider reading our blog post on this decision at
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
for more details. TL;DR is that it's more beneficial in the
long run to explicitly add which proposals to use.
For a more automatic migration, we have updated babel-upgrade,
https://github.com/babel/babel-upgrade to do this for you with
"npx babel-upgrade".
If you want the same configuration as before:
{
"plugins": [
// Stage 2
["#babel/plugin-proposal-decorators", { "legacy": true }],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
// Stage 3
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
["#babel/plugin-proposal-class-properties", { "loose": false }],
"#babel/plugin-proposal-json-strings"
]
}
If you're using the same configuration across many separate projects,
keep in mind that you can also create your own custom presets with
whichever plugins and presets you're looking to use.
module.exports = function() {
return {
plugins: [
require("#babel/plugin-syntax-dynamic-import"),
[require("#babel/plugin-proposal-decorators"), { "legacy": true }],
[require("#babel/plugin-proposal-class-properties"), { "loose": false }],
],
presets: [
// ...
],
};
};
my package.json:
{
"name": "react-notify",
"version": "0.1.0",
"description": "Push notification component for React",
"main": "dist/index.js",
"module": "dist/index.js",
"babel": {
"presets": [
"#babel/react",
"#babel/env",
"#babel/stage-2"
]
},
"license": "MIT",
"dependencies": {
"#babel/runtime": "^7.11.2",
"#fortawesome/fontawesome-svg-core": "^1.2.30",
"#fortawesome/free-brands-svg-icons": "^5.14.0",
"#fortawesome/free-solid-svg-icons": "^5.14.0",
"#fortawesome/react-fontawesome": "^0.1.11",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3",
"styled-components": "^5.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "SET NODE_ENV=production && rm -rf dist && mkdir dist && npx babel src/components/Notification --out-dir dist --copy-files",
"test": "react-scripts test",
"eject": "react-scripts eject",
"storybook": "start-storybook -p 6006 -s public",
"build-storybook": "build-storybook -s public"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"resolutions": {
"styled-components": "^5"
},
"devDependencies": {
"#babel/cli": "^7.11.6",
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"#babel/preset-react": "^7.10.4",
"#babel/preset-stage-2": "^7.8.3",
"#storybook/addon-actions": "^6.0.21",
"#storybook/addon-essentials": "^6.0.21",
"#storybook/addon-links": "^6.0.21",
"#storybook/node-logger": "^6.0.21",
"#storybook/preset-create-react-app": "^3.1.4",
"#storybook/react": "^6.0.21",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.4",
"enzyme-to-json": "^3.5.0",
"react-addons-test-utils": "^15.6.2",
"react-is": "^16.13.1",
"react-test-renderer": "^16.13.1"
}
}
I tried :
npx babel-upgrade
But still facing the same issue.
My Action/index.js:
import React, { useContext } from "react"
import PropTypes from "prop-types"
import { Button, Wrapper } from "./Styled"
import Context from "../context"
const Action = ({ name, onClick }) => {
const { type } = useContext(Context);
if (!(typeof onClick === "function")) {
throw new Error("Action event should be a function")
}
return (< Wrapper >
<Button type={type} onClick={onClick}>{name}</Button>
</Wrapper >)
}
Action.propTypes = {
name: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired
}
export default Action
Why I faced this issue?
Babel had stopped supporting Stage Presets in the configuration. Read this article.
How to solve the issue?
By running this command :
npx babel-upgrade
Then:
npm install
This will replace the legacy dependencies with :
"devDependencies": {
"#babel/cli": "^7.11.6",
"#babel/core": "^7.11.6",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/plugin-proposal-decorators": "^7.0.0",
"#babel/plugin-proposal-export-namespace-from": "^7.0.0",
"#babel/plugin-proposal-function-sent": "^7.0.0",
"#babel/plugin-proposal-json-strings": "^7.0.0",
"#babel/plugin-proposal-numeric-separator": "^7.0.0",
"#babel/plugin-proposal-throw-expressions": "^7.0.0",
"#babel/plugin-syntax-dynamic-import": "^7.0.0",
"#babel/plugin-syntax-import-meta": "^7.0.0",
}
And replace the configuration with :
"babel": {
"presets": [
"#babel/react",
"#babel/env"
]
},

Rollup.js building error with material-ui layout-grid component included

I integrated Material UI into my Svelte project with help of "Svelte Material UI" package.
But it don't contains Material layout-grid component.
I installed it separately using yarn add "#material/layout-grid" command.
But now I'm getting error during build process:
[!] (plugin postcss) Error: Invalid CSS after "...ch $size in map": expected expression (e.g. 1px, bold), was ".keys(variables.$co"
node_modules/#material/layout-grid/mdc-layout-grid.scss
Error: Invalid CSS after "...ch $size in map": expected expression (e.g. 1px, bold), was ".keys(variables.$co"
at options.error (/media/hdd-home/d/WebServers/home/spadmin.org/public_html/todoapp/node_modules/node-sass/lib/index.js:291:26)
So, I gave up resolving it myself.
The project package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv ."
},
"devDependencies": {
"#mdi/js": "^5.3.45",
"#rollup/plugin-commonjs": "^12.0.0",
"#rollup/plugin-node-resolve": "^8.0.0",
"#smui/button": "^1.0.0-beta.21",
"#smui/card": "^1.0.0-beta.21",
"#smui/checkbox": "^1.0.0-beta.21",
"#smui/chips": "^1.0.0-beta.21",
"#smui/common": "^1.0.0-beta.21",
"#smui/form-field": "^1.0.0-beta.21",
"#smui/linear-progress": "^1.0.0-beta.21",
"#smui/textfield": "^1.0.0-beta.21",
"#smui/top-app-bar": "^1.0.0-beta.21",
"material": "^0.4.3",
"node-sass": "^4.14.1",
"rollup": "^2.3.4",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-livereload": "^1.0.0",
"rollup-plugin-postcss": "^3.1.1",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"svelte": "^3.0.0",
"svelte-preprocess": "^3.7.4"
},
"dependencies": {
"#material/layout-grid": "^6.0.0",
"sirv-cli": "^0.4.4"
}
}
And here is rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy';
import livereload from 'rollup-plugin-livereload';
import {terser} from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss';
import autoPreprocess from 'svelte-preprocess';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'scripts/app.js',
},
plugins: [
copy({
targets: [
{src: 'src/index.html', dest: '.'},
],
}),
svelte({
dev: !production,
emitCss: true,
css: css => {
css.write('css/app.css');
},
preprocess: autoPreprocess()
}),
resolve({
browser: true,
dedupe: ['svelte', '#material'],
}),
commonjs(),
postcss({
extract: 'css/app.css',
minimize: true,
sourceMap: true,
use: [
[
'sass', {
includePaths: [
'./theme',
'./node_modules',
],
},
],
],
}),
!production && serve(),
!production && livereload({watch: ['scripts', 'css', 'src', 'theme']}),
production && terser(),
],
watch: {
clearScreen: false,
},
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
});
}
},
};
}
It clearly tries to parse the scss file as css. So it probably misses the compile step. I can't find the scss rollup plugin in your package.json.
Check this, it could solve your problem: https://www.npmjs.com/package/rollup-plugin-scss

Can't get flowtype to work with babel. Unexpected token

ERROR in ./$Store.js
Module build failed: SyntaxError: ./$Store.js: Unexpected token, expected "{"
(24:39)
import Notification from '../$Notification'
export class ERStore extends StoreBase implements _Store {
^
Same with "type" and another flow annotations. I've tried to:
1) add #babel/preset-flow
2) add plugin-transform-flow-strip-types
3) add "#babel/plugin-syntax-flow"
4) updated all deps to latest versions available
5) different order of presets
.babelrc
{
"presets": [
["#babel/preset-env", {
"useBuiltIns": "entry",
"modules": "auto"
}],
"#babel/preset-react",
"#babel/preset-flow"
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }],
"lodash"
]
}
deps:
"webpack": "3.12.0",
"#babel/core": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/plugin-proposal-decorators": "^7.3.0",
"#babel/plugin-syntax-flow": "^7.2.0",
"#babel/plugin-transform-flow-strip-types": "^7.2.3",
"#babel/preset-env": "^7.3.1",
"#babel/preset-flow": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#babel/preset-stage-3": "^7.0.0",
"babel-loader": "^8.0.5",
UPDATE:
Interesting, but jest is working fine with babel-jest.
Loader usage:
{
test: /.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
babelrc: true
}
},
},
I had to set babel config in webpack.conf file explicitly.
.babelrc was working only partly.