I try to update my webpack+js+react-HelloWorld webapp (which worked fine) to use Typescript instead by following webpack's intro but my editor cann't find the react module (which is defined in package.json and i ran "npm install").
So the bundle.js-file is loaded, shouldn't typescript be compiled into that one?
src/index.tsx:
import * as React from "react";
import { render } from "react-dom";
const App = () => (<div>Hello React with Typescript</div>);
function createAppParent() {
let element = document.createElement('div');
document.body.appendChild(element);
return element;
}
render((
<App />
), createAppParent());
package.json:
{
"name": "hello_world_ts",
"version": "1.0.0",
"description": "minimal configuration of webpack react and sass using typescript",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open --config webpack.dev.js",
"build": "webpack --config webpack.prod.js"
},
"keywords": [],
"author": "me",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^0.1.17",
"html-webpack-plugin": "^2.30.1",
"ts-loader": "^3.5.0",
"typescript": "^2.7.1",
"uglifyjs-webpack-plugin": "^1.1.6",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.1",
"webpack-merge": "^4.1.1"
},
"dependencies": {
"#types/react": "^16.0.38",
"#types/react-dom": "^16.0.4",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"target": "es2017",
"jsx": "react",
"allowJs": true
},
"exclude": [
"node_modules",
"dist"
],
"include": [
"./src/**/*"
]
}
webpack.common.json:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.tsx',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: [
'ts-loader'
],
}
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Hello React+Typescript',
})
]
};
webpack.dev.json:
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
});
webpack.prod.json:
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
devtool: 'source-map',
plugins: [
new UglifyJSPlugin({
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
});
So what is missing?
UPDATE:
I use Visual Studio Code which displayed the message "[ts] Cannot find module 'react'", but it wasn't only the editor. After 'npm start' starting the devServer i got something like "react module not found" in the firefox console.
So why is everything working now, a day later? (rhetoric question) No errors in the compiler and the dev server output works fine. I know that a reload can sometimes help an IDE but also npm?? Strange stuff, but not problem left to solve.
problem disappeared for unknown reasons on computer restart. (This answer is to mark question as answered.)
you could try adding
"target": "ES6"
"module": "commonjs",
"moduleResolution": "node",
"baseUrl": "src",
"typeRoots": ["node_modules/#types"]
to compilerOptions
Related
I can't get the typings for Jest to work with Webpack 5 and TypeScript, I've tried other solutions for the same problem. The problem is only with "screen" and "toBeInTheDocument" in my example test below. I'm leaning toward it being an ESLint configuration issue.
I can't run the tests, they fail with Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'.. I'm using Yarn 3.1.0. I've tried this answer and many others, including importing the types through tsconfig.json. What am I doing wrong?
Example test (src/components/Example/spec/test.spec.tsx):
import * as React from 'react';
import { render, screen } from '#testing-library/react';
import { Example } from './Example';
import "#testing-library/jest-dom/extend-expect";
import "#testing-library/jest-dom";
test("Renders correctly", () => {
render(<Example />);
const example = screen.getByAltText("Example");
expect(example).toBeInTheDocument();
});
jest.config.js:
module.exports = {
// An array of directory names to be searched recursively up from the requiring module's location
moduleDirectories: ['node_modules', '<rootDir>/src'],
// A map to module names that allow stubbing out resources with a single module
moduleNameMapper: {
'\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
},
// Preset for our Jest configuration base
preset: 'ts-jest/presets/js-with-ts',
setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],
// Environment used for testing
testEnvironment: 'jsdom',
};
webpack.config.js:
/* eslint-disable */
const { ModuleFederationPlugin } = require('webpack').container;
const path = require('path');
const packageJsonName = require('./package.json').name;
const packageJsonDeps = require('./package.json').dependencies;
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src', 'index.ts'),
devServer: {
client: {
overlay: true,
},
static: {
directory: './dist',
},
port: 3001,
historyApiFallback: true
},
module: {
rules: [
{
test: /\.(tsx|ts|jsx)?$/,
//exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
experimentalWatchApi: true,
transpileOnly: true,
},
},
],
},
{
test: /\.js$/,
enforce: 'pre',
use: ['source-map-loader'],
},
],
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: 'auto',
},
resolve: {
cacheWithContext: false,
extensions: ['.js', '.ts', '.tsx', '.jsx'],
plugins: [
new TsconfigPathsPlugin({
configFile: path.resolve(__dirname, './tsconfig.json'),
}),
],
symlinks: false,
},
};
package.json:
{
"scripts": {
"start": "webpack-cli serve",
"build": "webpack --mode production",
"dev": "webpack serve --progress",
"test": "jest",
"test:coverage": "jest --coverage --watchAll=false",
"test:watch": "jest --watch"
},
"dependencies": {
"react": "17.0.2",
"react-router-dom": "^5.2.0",
},
"devDependencies": {
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "12.1.2",
"#testing-library/user-event": "13.5.0",
"#types/jest": "27.0.2",
"#types/react": "^17.0.33",
"#types/react-router-dom": "5.3.2",
"#typescript-eslint/eslint-plugin": "5.2.0",
"#typescript-eslint/parser": "4.33.0",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-import": "2.25.2",
"eslint-plugin-jest": "25.2.2",
"eslint-plugin-react": "7.26.1",
"eslint-plugin-react-hooks": "4.2.0",
"jest": "^27.3.1",
"prettier": "2.4.1",
"ts-jest": "^27.0.7",
"ts-loader": "^9.2.6",
"tslib": "^2.3.1",
"typescript": "~4.3.5",
"webpack": "5",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.3.1"
}
}
And tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"declaration": true,
"esModuleInterop": true,
"importHelpers": true,
"jsx": "react",
"lib": ["es6", "dom"],
"module": "esnext",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"outDir": "dist",
"resolveJsonModule": true,
"rootDir": ".",
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "es6"
},
"include": ["**/*.ts", "**/*.tsx", "**/*.jsx", "**/*.js"],
"exclude": [
"dist",
"node_modules"
]
}
And setupTests.ts is just: import '#testing-library/jest-dom/extend-expect';
Thanks for any pointers.
Install the types using:
npm i #types/testing-library__jest-dom -D
Please make sure that the correct types are installed in your project. i.e.
npm i -D #testing-library/jest-dom#^4.2.4
From my experience the Typescript types seem to be missing from version 5.x
I'am creating a new project. As I completed installing npm packages and ran the basic setup, all worked fine, except, when I made changes in my code and saved the file and moved to browser to see the changes, the page was not reloaded in the browser. I have to refresh page manually to see the new changes.
Here is my package.json file :
{
"name": "resume",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#babel/preset-react": "^7.12.10",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#babel/preset-env": "^7.12.11",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.1",
"webpack": "^5.12.2",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^3.11.1"
}
}
Here is my webpack.config.js:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { web } = require('webpack')
module.exports = {
mode: 'development',
devServer: {
historyApiFallback: true,
contentBase: path.resolve(__dirname, './dist'),
open: true,
compress: true,
hot: true,
port: 8080,
},
target: 'web',
// entry: {
// main: path.resolve(__dirname, './src/index.js'),
// },
// output: {
// path: path.resolve(__dirname, './dist'),
// filename: '[name].bundle.js',
// },
module: {
rules: [
// JavaScript
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'webpack Boilerplate',
template: path.resolve('./index.html'),
filename: 'index.html', // output file
}),
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
],
}
I searched the web and it seems like the problem is with webpack-dev-server, but I'am not sure. Plz help.
Update webpack-dev-server version to 4.0.0-beta.0 I had the same issue too.
Trying to include files from my react project (create with create-react-app) with webpack using typescript, but I get these errors:
Seems like the loader, ts-loader, is having issues with my interfaces and static functions.
tsconfig.json:
{
"compilerOptions": {
"lib": ["es2017"],
"removeComments": true,
"moduleResolution": "node",
"noUnusedLocals": true,
"noUnusedParameters": true,
"sourceMap": true,
"target": "es2017",
"outDir": "lib"
},
"include": ["./**/*.ts", "../src/**/*.tsx"],
"exclude": [
"node_modules/**/*",
".serverless/**/*",
".webpack/**/*",
"_warmup/**/*",
".vscode/**/*"
]
}
webpack.config.js:
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
context: __dirname,
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
entry: slsw.lib.entries,
//entry: path.join(__dirname, "../index.tsx"),
devtool: slsw.lib.webpack.isLocal ? 'cheap-module-eval-source-map' : 'source-map',
resolve: {
extensions: ['.mjs', '.json', '.ts', '.tsx'],
symlinks: false,
cacheWithContext: false,
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js',
},
target: 'node',
externals: ['aws-sdk'],
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{
test: /\.ts|\.tsx$/,
loader: 'ts-loader',
include: [
path.resolve(__dirname, '../src/**/*'),
],
exclude: [
[
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, '.serverless'),
path.resolve(__dirname, '.webpack'),
],
],
options: {
transpileOnly: true,
experimentalWatchApi: true,
},
},
],
},
plugins: [
// new ForkTsCheckerWebpackPlugin({
// eslint: true,
// eslintOptions: {
// cache: true
// }
// })
],
};
Note - this webpack.config file resides in a neighbouring folder to the src folder due to it being used for AWS lambdas.
package.json:
{
"name": "sls",
"version": "1.0.0",
"description": "Serverless webpack example using Typescript",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"source-map-support": "^0.5.10"
},
"devDependencies": {
"#types/aws-lambda": "^8.10.17",
"#types/node": "^10.12.18",
"fork-ts-checker-webpack-plugin": "^3.0.1",
"serverless-webpack": "^5.2.0",
"ts-loader": "^5.3.3",
"typescript": "^3.2.4",
"webpack": "^4.29.0",
"aws-sdk": "^2.737.0",
"webpack-node-externals": "^1.7.2"
},
"author": "The serverless webpack authors (https://github.com/elastic-coders/serverless-webpack)",
"license": "MIT"
}
How to solve these errors? Thanks in advance.
I get an error when importing #material-ui to my React component.
Module not found: Error: Can't resolve './utils.
I can import other libraries like lodash but with #material-ui there's issue. I tried reinstall node_modules but error still occur.
import React, { useEffect } from "react";
import _ from "lodash";
import Button from "#material-ui/core";
export default function Dashboard() {
useEffect(() => {
console.log("Test");
const testVar = "test";
console.log(_.split(testVar));
return () => {
// cleanup;
};
}, []);
return (
<div>
<Button>Login</Button>
</div>
);
package.json
{
"name": "views",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"#material-ui/core": "^4.10.2",
"#material-ui/icons": "^4.9.1",
"lodash": "^4.17.15",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#types/lodash": "^4.14.157",
"#types/react": "^16.9.38",
"#types/react-dom": "^16.9.8",
"source-map-loader": "^1.0.0",
"ts-loader": "^7.0.5",
"typescript": "^3.9.5",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode=development --watch --progress",
"dev:nowatch": "webpack --mode=development"
},
"keywords": [],
"author": "",
"license": "ISC"
}
webpack.config.js
var path = require("path");
module.exports = {
mode: "development",
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
entry: {
dashboard: "./Dashboard/index",
// creator: "./Creator/index",
},
output: {
path: path.resolve(__dirname, ""),
filename: "./[name]/dist/index.js",
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"],
modules: [path.resolve(__dirname, "./"), "node_modules"],
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader",
},
],
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader",
},
],
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
react: "React",
"react-dom": "ReactDOM",
},
};
tsconfig.json
{
"compilerOptions": {
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"outDir": "./dist/",
"sourceMap": true,
"target": "es5",
"jsx": "react",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
Example errors
ERROR in ./node_modules/#material-ui/core/esm/index.js
Module not found: Error: Can't resolve './withMobileDialog' in 'C:\Users\user\Documents\Code\calendarapp\UI\Client\views\node_modules\#material-ui\core\esm'
# ./node_modules/#material-ui/core/esm/index.js 240:0-65 240:0-65 241:0-35 241:0-35
# ./Dashboard/Dashboard.tsx
# ./Dashboard/App.tsx
# ./Dashboard/index.tsx
ERROR in ./node_modules/#material-ui/core/esm/index.js
Module not found: Error: Can't resolve './withWidth' in 'C:\Users\user\Documents\Code\calendarapp\UI\Client\views\node_modules\#material-ui\core\esm'
# ./node_modules/#material-ui/core/esm/index.js 242:0-51 242:0-51 243:0-28 243:0-28
# ./Dashboard/Dashboard.tsx
# ./Dashboard/App.tsx
# ./Dashboard/index.tsx
Found solution.
In webpack.config.js add ".js", ".jsx" to resolve.
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
If I can add something and if I remember correctly, the import Button from "#material-ui/core"; should have curly brackets around "Button" like so import {Button} from "#material-ui/core";
First create your react app
Then
Install material ui core and icons modules
Then
Go package.json and check dependencies if found material ui core and icons then first copy icons line
Then paste on file which u use like as index.js
Then
U only add /icon name
For example:-
Import add from #material-ui/icons
You add only
#material-ui/icons/add
💯% solved with proof
I have a React build configuration using Webpack, ESlint, Prettier and TypeScript.
When I run the build it looks like I'm getting TypeScript linting errors that should be nullified by the #typings/react or #typings/react-dom packages.
Looking at the documentation I shouldn't need to define accessibility modifiers or return types for React Components: https://www.typescriptlang.org/docs/handbook/jsx.html
This seems like the same issue as here: Missing return type on function - in react (typescript) code
but installing the typings packages hasn't resolved the issue for me. Please note, I have also tried removing the #typings/react package as the #typings/react-dom has this as a dependency and this doesn't resolve the issue.
Webpack config
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const path = require('path');
const createWebpackConfig = () => {
const isProd =
process.env &&
process.env.NODE_ENV &&
process.env.NODE_ENV === 'production';
return {
entry: ['#babel/polyfill', './index.tsx'],
mode: isProd ? 'production' : 'development',
module: {
rules: [
{
enforce: 'pre',
test: /(\.jsx|\.js|\.ts|\.tsx)$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /(\.jsx|\.js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
},
{
test: /(\.tsx|\.ts)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-typescript',
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
}
]
},
resolve: {
modules: [path.resolve(__dirname, '/'), 'node_modules'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
enforceExtension: false
},
target: 'web',
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor'
},
main: {
name: 'main'
}
}
}
},
output: {
path: path.join(__dirname, 'bundles'),
filename: '[name].app.js',
chunkFilename: '[name].bundle.js',
pathinfo: true
},
plugins: [
new CaseSensitivePathsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(isProd ? 'production' : 'development')
}
})
]
};
};
module.exports = createWebpackConfig;
ESLint config
{
"parser": "#typescript-eslint/parser", // Specifies the ESLint parser
"extends": [
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended", // Uses the recommended rules from the #typescript-eslint/eslint-plugin
"prettier/#typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from #typescript-eslint/eslint-plugin that would conflict with prettier
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
"parserOptions": {
"ecmaVersion": 10, // Allows for the parsing of modern ECMAScript features
"sourceType": "module", // Allows for the use of imports
"jsx": true
},
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"endOfLine": "auto"
}
]
}
}
tsconfig.json
{
"compilerOptions": {
"module": "esnext",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"jsx": "preserve"
},
"exclude": ["node_modules"]
}
package.json
{
"name": "reacttypescripttest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "cross-env NODE_ENV=development webpack --config ./webpack.config.js --progress --colors --watch --display-error-details"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-proposal-object-rest-spread": "^7.5.5",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "^7.0.0",
"#babel/preset-typescript": "^7.3.3",
"#types/react": "^16.8.24",
"#types/react-dom": "^16.8.5",
"#typescript-eslint/eslint-plugin": "^1.13.0",
"#typescript-eslint/parser": "^1.13.0",
"babel-loader": "^8.0.6",
"case-sensitive-paths-webpack-plugin": "^2.2.0",
"cross-env": "^5.2.0",
"eslint": "^6.1.0",
"eslint-config-prettier": "^6.0.0",
"eslint-loader": "^2.2.1",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-react": "^7.14.3",
"mini-css-extract-plugin": "^0.8.0",
"prettier": "^1.18.2",
"prettier-eslint": "^9.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"typescript": "^3.5.3",
"webpack-cli": "^3.3.6"
},
"devDependencies": {
"webpack": "^4.39.1"
}
}
File causing error (index.tsx)
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return <div>Running!</div>;
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Errors
5:3 error Missing accessibility modifier on method definition render #typescript-eslint/explicit-member-accessibility
5:9 warning Missing return type on function #typescript-eslint/explicit-function-return-type
The first error Missing accessibility modifier on method definition render is saying that you did not declare your render method as public or private or any other type (more reading on types. When working with Typescript all class methods need to have be declared accordingly, depending if you want to have them accessible outside your class instance or not. For render method it should be public. Code below should work nicely for you:
public render() {
return <div>Running!</div>;
}
When it comes the 2nd error your're having, it means that your linter expects the render method to have declared what's the output of its' execution. The correct type for render method is React.ReactNode, so your final code should look like below (assuming you're not importing ReactNode in the import statement earlier)
public render(): React.ReactNode {
return <div>Running!</div>;
}
Edit 1
Even if TS itself doesn't require all these annotations, the linter you're using does. See their default rules- as you can see, the rules you're having trouble with are not turned off. The solution there would be disabling them in your app eslint config, like below:
"rules": {
"#typescript-eslint/explicit-function-return-type": "off",
"#typescript-eslint/explicit-member-accessibility": "off"
}
If anyone is running into this AND using a tsx file already. Makre sure that you've configured vscode to associate tsx files with TypescriptReact and not just Typescript. When the tsx file is open, bottom right click on Typescript and set association.