I'm converting my .js files to .tsx because I want to work with TypeScript.
I added TypeScript with yarn add typescript #types/node #types/react #types/react-dom #types/jest and started to convert index.tsx then App.tsx
With tsx extension I get this error :
Error: Cannot find module './App'
at webpackMissingModule (bundle.js:16:50)
at ./src/index.tsx (bundle.js:16:130)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at startup:7:1
at startup:7:1
With .js extension, everything works fine.
Here is my package.json
{
"name": "workout_generator",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.10.0",
"#emotion/styled": "^11.10.0",
"#headlessui/react": "^1.6.6",
"#mui/material": "^5.9.3",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^14.4.2",
"#types/jest": "^28.1.6",
"#types/node": "^18.6.4",
"#types/react": "^18.0.15",
"#types/react-dom": "^18.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.4.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"typescript": "^4.7.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.8",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.8"
}
}
Any idea where is my mistake ?
You need to inform webpack it needs to parse tsx files as well. I'm not familiar with Create-React-App, but if you run yarn eject you will have access to the webpack.config.js file.
In the field resolvejust add tsx:
resolve: {
extensions: [".ts", ".tsx", ".js", "jsx", ".json"]
}
You will also need a tsconfig.json file. It generally looks like this:
{
"compilerOptions": {
"outDir": "./build/",
"baseUrl": "./",
"skipLibCheck": true,
"noEmit": true,
"noImplicitAny": false,
"downlevelIteration": true,
"lib": ["es6", "es2019.array", "dom"],
"rootDir": "src",
"module": "commonjs",
"target": "es5",
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"jsx": "react",
"allowJs": true
},
"include": ["./src/**/*", "./custom.d.ts"],
"exclude": ["node_modules"]
}
Last but not least, you will need to use #babel/preset-typescript in your .babelrc file.
{
"presets": [
"#babel/preset-env",
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
If it sounds like too much trouble, I'd recommend using alright-react-app, or to recreate a project from scratch with the --typescript flag.
Related
I created a .scss module and I'am trying to import it in a .tsx of a react project of mine, but it keeps bumping into the ts(2307) error.
Trying to import like this:
import styles from './Input/Input.module.scss';
Already tried to reinstall Sass, types#Sass and css.modules, to update all the project dependencies, to copy given project's src folder and paste over the src of a downloaded project with working .scss imports, to create a declaration.d.ts file with the module declaration, but nothing worked out, keeps showing the ts(2307) message (I'm using VScode, don't know if it has anything to do).
Someone has any idea how can I fix this?
package.json file contains:
{
"name": "challenge",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^14.4.3",
"#types/jest": "^29.4.0",
"#types/node": "^18.11.19",
"#types/react": "^18.0.27",
"#types/react-dom": "^18.0.10",
"classnames": "^2.3.2",
"normalize.css": "^8.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.7.1",
"react-router-dom": "^6.8.1",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^5.51.0",
"#typescript-eslint/parser": "^5.51.0",
"eslint": "^8.33.0",
"eslint-plugin-react": "^7.32.2",
"sass": "^1.58.0",
"typescript-plugin-css-modules": "^4.1.1"
}
}
and
tsconfig.json contains
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "src"
},
"include": [
"src"
]
}
I am publishing a react library which is written in typescript. And it is transpiled into
Javascript in the build. Inside typescript I am using baseUrl in tsconfig.json and referring absolute path as follows
import CollabsibleMenu from 'components/collapsibleMenu';
It works well inside typescript but after I build it and try to use the package in another project it throws error
error - ./node_modules/aaarc-react/dist/components/verticalMenu/index.js:7:0
Module not found: Can't resolve 'components/collapsibleMenu'
This is my tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"esModuleInterop": true,
"declaration": true,
"importHelpers": true,
"module": "commonjs",
"outDir": "dist",
"lib": ["ES5", "ES2015", "ES2016", "DOM", "ESNext"],
"rootDirs": [
"./src"
],
"allowSyntheticDefaultImports": true,
"jsx": "react-jsx",
"skipLibCheck": true,
"types": ["node"],
"moduleResolution": "node",
"noImplicitAny": true,
"noUnusedLocals": true,
"sourceMap": true,
"strict": true,
"target": "es6",
"noEmit": false
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}
And this is my package.json
{
"name": "aaarc-react",
"version": "0.1.0",
"private": true,
"module": "dist/index.js",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"#types/jest": "^27.5.2",
"#types/node": "^16.11.39",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"date-fns": "^2.28.0",
"grommet": "^2.24.0",
"grommet-icons": "^4.7.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"styled-components": "^5.3.5",
"typescript": "^4.7.3",
"web-vitals": "^2.1.4"
},
"peerDependencies": {
"react": "^18.1.0",
"react-dom": "^18.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "rm -rf dist/ && tsc && cp tsconfig.json dist/jsconfig.json",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/styled-components": "^5.1.25"
}
}
Thank you!!!
Please use this
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.js"]
Am using rollup.js to create a react library but when i run npm run build i get an error
as if useState hook is tried to be retrieved from null
Uncaught TypeError: Cannot read properties of null (reading 'useState')
at Object.useState (react.development.js:1617:1)
at ReactPokableLoving (index.esm.js:20:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
here my rollup.config.js
import { babel } from "#rollup/plugin-babel";
const config = {
input: "src/lib/index.js",
output: {
file: "dist/index.esm.js",
format: "esm",
},
external: [/#babel\/runtime/, "react", "react-dom"],
plugins: [
babel({
babelHelpers: "runtime",
plugins: ["#babel/plugin-transform-runtime"],
}),
],
};
export default config;
my .babelrc
{
"presets" : [["#babel/preset-env", {"targets" : "defaults"}],[
"#babel/preset-react",
{
"runtime": "automatic"
}
]]
}
and my package.json
{
"name": "xxxxx",
"version": "1.0.7",
"author": "ndotie",
"keywords": [
"react",
"components",
"ui",
"pagination"
],
"module": "dist/index.esm.js",
"repository": {
"type": "git",
"url": "https://github.com/xxx/xxxx.git"
},
"files": [
"dist",
"README.md"
],
"private": false,
"dependencies": {
"#babel/polyfill": "^7.12.1",
"#babel/runtime": "^7.17.9",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^12.1.4",
"#testing-library/user-event": "^13.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.0",
"rollup": "^2.70.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test",
"eject": "react-scripts eject",
"prebuild": "rimraf dist",
"build": "rollup -c"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"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/cli": "^7.17.6",
"#babel/core": "^7.17.9",
"#babel/plugin-transform-runtime": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#rollup/plugin-babel": "^5.3.1",
"cross-env": "^7.0.3"
}
}
I face the same problem and had success to resolve that, you missing some configuration in your rollup.config file:
external: ["react", "react-dom"]
I will attach my full configuration to create an npm package with rollup, react(18) and typescript.
rollup.config.js file:
//This plugin prevents packages listed in peerDependencies from being bundled with our component library
import peerDepsExternal from "rollup-plugin-peer-deps-external";
//efficiently bundles third party dependencies we've installed and use in node_modules
import resolve from "#rollup/plugin-node-resolve";
// //enables transpilation into CommonJS (CJS) format
import commonjs from "#rollup/plugin-commonjs";
//transpiled our TypeScript code into JavaScript. This plugin will use all the settings we have set in tsconfig.json.
//We set "useTsconfigDeclarationDir": true so that it outputs the .d.ts files in the directory specified by in tsconfig.json
import typescript from "rollup-plugin-typescript2";
// transforms our Sass into CSS. In order to get this plugin working with Sass, we've installed sass
import postcss from "rollup-plugin-postcss";
const packageJson = require("./package.json");
export default {
input: "src/index.tsx",
output: [
{
file: packageJson.module,
format: "esm", // import '' from '...
sourcemap: true,
},
],
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({ useTsconfigDeclarationDir: true }),
postcss(),
],
external: ["react", "react-dom"],
};
ts.config file:
{
"compilerOptions": {
"target": "es5",
"outDir": "build",
"lib": ["dom", "dom.iterable", "esnext"],
"declaration": true,
"declarationDir": "build",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": false,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "./src"
},
"include": ["src"],
"exclude": ["node_modules", "build"]
}
package.json file:
{
"name": "test",
"version": "1.0.0",
"main": "build/index.js",
"module": "build/index.js",
"scripts": {
"build": "rollup -c",
"build-watch": "rollup -c -w"
},
"license": "MIT",
"devDependencies": {
"#rollup/plugin-commonjs": "^22.0.0",
"#rollup/plugin-node-resolve": "^13.3.0",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"rollup": "^2.75.6",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.31.2",
"sass": "^1.52.1",
"typescript": "^4.6.4",
"react": "^18.1.0",
"react-dom": "^18.1.0",
}
}
NOTE: if you are testing the library using npm link with react application you should remove the react and react-dom dependencies from your package and instead of that you should link the library to the react and react-dom that found in your application, this is done to avoid the double copy of react when you test the library (read more here )
I've created a Typescript, React project that makes use of Storybook.js, that contains all of my components, styling and images for the project I'm working on.
I package this project with the help of Webpack and then via an Azure pipeline I build and publish it to a private feed. I then install the package(npm install) with no problems on my main project, which is a Typescript, Next.js project. When I try to import the package into a page,
import {Footer} from '#private_feed/generic.project/dist/bundle.js'
I get the error mentioned in the title, along with:
./node_modules/next/dist/next-server/server/require.js
Critical dependency: the request of a dependency is an expression
./node_modules/next/dist/next-server/server/load-components.js
Critical dependency: the request of a dependency is an expression
> Build error occurred
ReferenceError: document is not defined
I had it working before when i had no css and no images. I was compiling down my Typescript with tsc and all my styling was making use of styled-components. However, for project and team related reasons I need to be able to make use of css files and unfortunately not use styled-components.
The following files belong to the project that is being packaged.
package.json
{
"name": "#private_feed/generic.project",
"version": "0.1.11",
"files": [
"dist"
],
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"#types/jest": "^24.9.1",
"#types/node": "^12.12.47",
"#types/react": "^16.9.41",
"#types/react-dom": "^16.9.8",
"#types/styled-components": "^5.1.0",
"cross-env": "^7.0.2",
"lodash": "^4.17.15",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"styled-components": "^5.1.1"
},
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test",
"eject": "react-scripts eject",
"storybook": "start-storybook -p 9009 -s public",
"build-storybook": "build-storybook -s public",
"build": "webpack"
},
"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": {
"#storybook/addon-actions": "^5.3.19",
"#storybook/addon-knobs": "^5.3.19",
"#storybook/addon-links": "^5.3.19",
"#storybook/addons": "^5.3.19",
"#storybook/preset-create-react-app": "^3.1.2",
"#storybook/react": "^5.3.19",
"#types/lodash": "^4.14.157",
"css-loader": "^3.6.0",
"file-loader": "^6.0.0",
"style-loader": "^1.2.1",
"ts-loader": "^7.0.5",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
},
"babel": {
"presets": [
"react-app"
]
},
"description": "This project was bootstrapped with [Create React App].",
"author": "",
"license": "ISC"
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg)$/,
use: [
'file-loader',
],
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"es2015"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react",
"noImplicitAny": true,
"sourceMap": true,
"typeRoots": ["./src/#types", "./node_modules/#types"]
},
"include": [
"src", "types"
]
}
src/#types/assets/index.d.ts
declare module "\*.svg" {
import React = require("react");
export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
declare module "\*.css" {
const content: string;
export default content;
}
Is it possible to use export * from './X' with absolute import paths and eslint in react/typescript? I wanted to have single index.ts file in components folder that would export everything else but eslint gives me weird error when i'm trying to do this.
My current structure looks like this:
src/components/Example1/Example1.tsx
import React from 'react';
export type Props = {};
export const Example1 = (props: Props) => <div></div>
src/components/Example1/index.ts
export * from './Example1';
src/components/index.ts
export * from './Example1';
Both index files gives me error:
0:0 error Parsing error: Cannot read property 'name' of undefined
Also when i try to import anything from the components/index file using an absolute path import { Example1 } from 'components'; i have an error:
1:43 error Parse errors in imported module 'components': Cannot read property 'name' of undefined (undefined:undefined) import/namespace
1:43 error Parse errors in imported module 'components': Cannot read property 'name' of undefined (undefined:undefined) import/named
This is my .eslintrc.json file
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"root": true,
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:#typescript-eslint/eslint-recommended",
"plugin:import/warnings",
"plugin:import/errors",
"plugin:import/typescript",
"prettier/#typescript-eslint",
"prettier",
"prettier/react"
],
"plugins": [
"react",
"react-hooks",
"jsx-a11y",
"#typescript-eslint",
"prettier"
],
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"settings": {
"react": {
"version": "detect"
},
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"moduleDirectory": ["node_modules", "src/"]
}
}
},
"rules": {
"prettier/prettier": "error",
"import/newline-after-import": "error",
"no-unused-vars": "off",
"#typescript-eslint/no-unused-vars": [
"warn",
{ "args": "after-used", "argsIgnorePattern": "^_" }
]
}
}
This is my tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "./src"
},
"include": ["src"]
}
My current package.json:
{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"private": true,
"dependencies": {
"#apollo/react-hooks": "^3.1.3",
"#material-ui/core": "^4.9.5",
"#material-ui/icons": "^4.9.1",
"#material-ui/styles": "^4.9.0",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"#types/jest": "^24.0.0",
"#types/material-ui": "^0.21.7",
"#types/node": "^12.0.0",
"#types/react": "^16.9.0",
"#types/react-dom": "^16.9.0",
"#types/react-router-dom": "^5.1.3",
"#types/styled-components": "^5.0.1",
"#types/yup": "^0.26.32",
"apollo-boost": "^0.4.7",
"env-cmd": "^10.1.0",
"formik": "^2.1.4",
"graphql": "^14.6.0",
"i18next": "^19.3.3",
"i18next-browser-languagedetector": "^4.0.2",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-i18next": "^11.3.3",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.0",
"styled-components": "^5.0.1",
"typescript": "~3.7.2",
"yup": "^0.28.3"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^2.23.0",
"#typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^3.1.2",
"prettier": "^1.19.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build:staging": "env-cmd -f .env.staging yarn build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lint": "tsc --noEmit && eslint . --ext .js,.tsx,.ts --max-warnings=0",
"lint:fix": "eslint . --ext .js,.tsx,.ts --fix",
"watch": "react-scripts start",
"deploy": "yarn build && firebase deploy",
"deploy:staging": "yarn build:staging && firebase use staging && firebase deploy"
},
"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"
]
}
}
I'm also using lerna with yarn workspaces to easily handle MERN app.
Deleting eslint package / configs, node_modules did not help me, i still have Cannot read property 'name' of undefined error. It is super weird because in clean CRA everything works. I spent last 4 hours trying to solve this problem and finally used a workaround with importing types to root index file and reexporing them as new type but it's definately a painful solution. I need to keep isolatedModules. Maybe someone had similar problem?
The problem was #typescript-eslint package, check out the issue for more info:
https://github.com/typescript-eslint/typescript-eslint/issues/1746
Fast fix for this is to downgrade packages to version 2.22.0:
#typescript-eslint/eslint-plugin
#typescript-eslint/parser
#Edit This helped with lint error but my CRA build is still crashing, I guess i will have to wait for package fix