Can't import React component from another file - reactjs

I'm new to react and I'm having issues with importing a component from another file.
import React from 'react';
import ReactDOM from 'react-dom';
import '../resources/styles.scss';
import WelcomeView from '../views/welcome/WelcomeView';
const Root: React.FC = () => {
return (
<div>
<WelcomeView />
</div>
);
};
ReactDOM.render(<Root />, document.getElementById('root'));
With the above code, I get this error: Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
I've been googling this for hours and everyone has been saying that it's an import issue, but I think I'm using my exports correctly.
Here is the WelcomeView component which I'm trying to import from another file:
import styles from './WelcomeView.scss';
import React from 'react';
const WelcomeView: React.FC = () => {
return (
<div className={styles.welcome}>
Welcome
</div>
);
};
export default WelcomeView;
If I inline WelcomeView in the same file as my Root component, then it works. But doesn't work when it's in a separate file. I think it might have something to do with my tsconfig?
{
"compilerOptions": {
"esModuleInterop": true,
"isolatedModules":true,
"jsx": "react",
"lib": ["esnext", "dom"],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"noEmit": true,
"target": "es5",
"forceConsistentCasingInFileNames": true,
"importHelpers": true,
"skipLibCheck": true,
"strict": true,
"incremental": true,
"noFallthroughCasesInSwitch": true
},
"include": ["frontend/src/root/app.tsx"],
}
My package.json dependencies:
"devDependencies": {
"#teamsupercell/typings-for-css-modules-loader": "^2.4.0",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#babel/cli": "^7.1.0",
"#babel/core": "^7.1.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.2.1",
"awesome-typescript-loader": "^5.2.1",
"css-loader": "^1.0.1",
"node-sass": "^5.0.0",
"sass-loader": "^10.1.0",
"style-loader": "^2.0.0",
"typescript": "^4.1.2",
"webpack": "^4.40.2",
"webpack-cli": "^3.1.1"
},
"dependencies": {
"react": "^16.5.2",
"react-dom": "^16.5.2"
}
Webpack:
const path = require('path');
module.exports = {
entry: './frontend/src/root/root.tsx',
mode: 'development',
module: {
rules: [
{
test: /\.scss$/,
loaders: [
'style-loader',
'#teamsupercell/typings-for-css-modules-loader',
'css-loader?modules',
'sass-loader',
],
},
{
test: /\.(ts|tsx)$/,
loader: 'awesome-typescript-loader',
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: { presets: ['#babel/env'] },
},
],
},
resolve: { extensions: ['*', '.css', '.scss', '.ts', '.tsx', '.js', '.jsx'] },
output: {
path: path.resolve(__dirname, 'frontend/public/'),
filename: 'bundle.js',
},
};

It may be caused by re-importing the relevant component or by different case among the connected components.

Try to include your entire src folder in tsconfig include.

Okay this is kind of underwhelming, but it turns out the files were corrupt since I'm using OSX. I figured it out from this question:
webpack --watch isn't compiling changed files
I just deleted all the files and then recreated them and it worked.

Related

React v18 + MUI v5 + Weback 5 : Not working when create as npm package

I am trying to create simple react package that can be used in react apps.
I am using these main libraries: React(18.2.0), Webpack(5.4.0), mui/material(5.11.2), typescript(4.9.4).
I am adding this package in my react app using local dependency("packagename": "file:../package").
It is working fine without mui. But when i add mui it's building fine in package but gives error in react app where package is used.
Below is webpack configurations of package.
const path = require("path");
const webpack = require("webpack");
module.exports = (env) => ({
mode: env.NODE_ENV,
watch: env.NODE_ENV === "development",
entry: {
app: path.join(__dirname, "src", "index.tsx"),
},
output: {
libraryTarget: "umd",
library: "libname",
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: "/node_modules/",
options: {
configFile: path.resolve(__dirname, "tsconfig.json"),
},
},
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 1,
modules: {
auto: true,
localIdentName:
env.NODE_ENV === "development"
? "[local]__[hash:base64:5]"
: "[hash:base64:5]",
},
},
},
],
include: /\.module\.css$/,
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
exclude: /\.module\.css$/,
},
{
test: /\.svg$/,
use: [
{
loader: "#svgr/webpack",
options: {
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
},
},
{
loader: "svg-url-loader",
},
],
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: "url-loader",
},
],
},
{
test: /\.(woff|woff2)$/,
use: {
loader: "url-loader",
},
},
],
},
plugins: [
new webpack.DefinePlugin({
"process.env.STAGE": JSON.stringify(env.STAGE),
}),
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
],
externals: {
react: {
commonjs: "react",
commonjs2: "react",
amd: "react",
root: "React",
},
"react-dom": {
commonjs: "react-dom",
commonjs2: "react-dom",
amd: "react-dom",
root: "ReactDOM",
},
},
});
This is package.config.
"dependencies": {
"#emotion/react": "^11.10.5",
"#emotion/styled": "^11.10.5",
"#mui/material": "^5.11.2"
},
"devDependencies": {
"#svgr/webpack": "^5.4.0",
"#types/node": "^12.12.42",
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.10",
"css-loader": "^4.3.0",
"style-loader": "^1.3.0",
"svg-url-loader": "^6.0.0",
"ts-loader": "^8.0.7",
"typescript": "^4.9.4",
"url-loader": "^4.1.1",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0",
"webpack-node-externals": "^3.0.0"
},
"files": [
"dist/index.js",
"dist/index.d.ts",
"dist/*.png",
"dist/*.jpg"
],
"peerDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
Below is tsconfig.json
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"downlevelIteration": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react",
"allowJs": true,
"declaration": true,
"outDir": "./dist"
},
I am getting below error in react app in which package is used. That reach app is created using create-react-app and using latest react v18.
I tried researching and tried by changing several options in webpack config as well. But i am not able to figure this out.
Any help is appriciated.
React 18 introduces a new root API, Change your index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
For Typescript:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

CSS class not applying when using SASS in Webpack(5)/React project with Typescript

I have this new project being assembled with Webpack 5 + React 16 + TypeScript 4 and willing to use SASS.
I have set all loaders, but yet the class does not apply on the html elements, when I say "class" it's exactly what I mean, if I style directly an element it does work.
I my main.scss main file (which is imported in the main app file App.tsx) if I put:
body { background-color: red; }
This works Ok!
But if I try to set the style using class like this:
.main-body-style {
background-color: red;
}
...
<body className="main-body-style">...</body>
This doesn't work, super weird!!
My very basic webpack.config.ts:
import path from "path";
import { Configuration, DefinePlugin } from "webpack";
import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import pjson from "./package.json";
const now = new Date();
const buildVersion = `v${pjson.version}-${
now.getDate().toString().padStart(2, "0") +
(now.getMonth() + 1).toString().padStart(2, "0") +
now.getFullYear() +
"." +
now.getHours().toString().padStart(2, "0") +
now.getMinutes().toString().padStart(2, "0")
}`;
const urlStoreMessage = "htpp://";
const __ = (argToStringfy: string) => JSON.stringify(argToStringfy);
const config: Configuration = {
entry: "./src/index.tsx",
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
},
{
test: /\.s(a|c)ss$/,
include: [path.resolve(__dirname, "src/assets")],
use: [
"style-loader",
{
loader: "css-loader",
options: { modules: true },
},
"sass-loader",
],
},
],
},
plugins: [
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: "./src/**/*.{ts,tsx,js,jsx}", //files: "./src/**/*",
},
}),
new DefinePlugin({
"process.env": process.env.production || !process.env.development,
BUILD_VERSION: __(buildVersion),
URL_STORE_MESSAGE: __(urlStoreMessage),
}),
],
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
},
devtool: "source-map",
devServer: {
static: path.join(__dirname, "build"),
compress: true,
liveReload: true,
open: false,
port: 4000,
},
};
export default config;
Basic .babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Basic tsconfig.json:
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"sourceMap": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true, // Babel is going to generate the typescript code
"jsx": "react", //
"module": "commonjs"
},
"include": ["src"]
}
.eslintrc.json:
{
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": ["#typescript-eslint", "react-hooks"],
"extends": [
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"react/prop-types": "off"
},
"settings": {
"react": {
"pragma": "React",
"version": "detect"
}
}
}
package.json:
...
"dependencies": {
"axios": "^0.24.0",
"bootstrap": "^4.4.1",
"history": "^5.1.0",
"react": "^16.8.6",
"react-bootstrap": "^1.6.1",
"react-bootstrap-icons": "^1.6.1",
"react-bootstrap-table": "^4.3.1",
"react-dom": "^16.8.6",
"react-router-dom": "^5.2.0",
"sass": "^1.43.4"
},
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/plugin-transform-runtime": "^7.16.0",
"#babel/preset-env": "^7.16.0",
"#babel/preset-react": "^7.16.0",
"#babel/preset-typescript": "^7.16.0",
"#babel/runtime": "^7.16.0",
"#types/bootstrap": "^5.1.6",
"#types/fork-ts-checker-webpack-plugin": "^0.4.5",
"#types/node-sass": "^4.11.2",
"#types/react": "^16.8.6",
"#types/react-bootstrap": "^0.32.28",
"#types/react-dom": "^16.8.6",
"#types/react-router-dom": "^5.3.2",
"#types/webpack": "^5.28.0",
"#types/webpack-dev-server": "^4.3.1",
"#typescript-eslint/eslint-plugin": "^5.3.0",
"#typescript-eslint/parser": "^5.3.0",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"css-modules-typescript-loader": "^4.0.1",
"eslint": "^7.32.0",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"fork-ts-checker-webpack-plugin": "^6.4.0",
"html-webpack-plugin": "^5.5.0",
"node-sass": "^6.0.1",
"sass-loader": "^12.3.0",
"style-loader": "^3.3.1",
"ts-node": "^10.4.0",
"typescript": "^4.4.4",
"webpack": "^5.62.1",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
...
And in a very basic App.tsx file:
import React from "react";
import TopBarMenu from "../components/TopBarMenu";
import "../assets/styles/main.scss";
const App: React.FC = () => {
return (
<>
<TopBarMenu />
</>
);
};
export default App;
What am I missing here?
I have other projects with Webpack and React, but without Typescript and with Webpack 4.
In webpack.config.ts , your have enabled modules in css-loader options for all css/scss files , and they will be treated as css module files.
refer to : https://github.com/css-modules/css-modules for usage.
a better implementation is to have 2 rules , one to handle the normal css/scss files and another to handle css/scss modules, like this :
{
test: /\.module\.(sa|sc|c)ss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: { modules: true }
},
'sass-loader'
]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /\.module\.(sa|sc|c)ss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
then all *.scss/css/sass files will be treated as normal ,
and all *.module.scss/css/sass will be treated as css modules

Webpack 5 & Jest - Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'

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

Module not found: Error: Can't resolve 'openlayers' in typescript

I'm trying to use openlayers with typescript, But there is a problem.
openlayers is used in MapSection component, below is the MapSection code
import React, { useLayoutEffect } from 'react'
import * as ol from 'openlayers';
const MapSection: React.FC = () => {
useLayoutEffect(() => {
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
})],
target: 'map-section',
view: new ol.View({
center: [36, 38],
zoom: 16,
}),
controls: [],
});
map.getKeys();
}, [])
return (
<section className='map-section'>
</section>
)
}
export default MapSection;
If I run webpack devServer, it gives error message like this
ERROR in ./src/components/MapSection.tsx Module not found: Error: Can't resolve 'openlayers' in '/Users/donghokim/recruit/angelswing-frontend-test-0.3/src/components' # ./src/components/MapSection.tsx 2:0-33 6:18-24 7:19-27 8:20-29 11:16-23 # ./src/components/App.tsx # ./src/index.tsx
It is weird that component try to find openlayers library in current directory.
webpack and tsconfig files are written like this
//webpack.config.js
import path from "path";
import HTMLWebpackPlugin from 'html-webpack-plugin';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import webpack from "webpack";
const config: webpack.Configuration = {
entry: path.join(__dirname, 'src', 'index.tsx'),
context: path.resolve(__dirname, '.'),
devtool: 'source-map',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './build'),
publicPath: '/'
},
resolve: {
extensions: ['.ts', '.tsx', '.js', 'json'],
modules: [
'node_modules',
path.resolve(__dirname, './node_modules')
],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
]
}
},
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
]
},
plugins: [
new HTMLWebpackPlugin({
template: './public/index.html'
}),
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: "./src/**/*",
},
}),
]
}
export default config;
//tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"outDir": "build",
"module": "CommonJS",
"target": "ES5",
"jsx": "react",
"moduleResolution": "node",
"experimentalDecorators": true,
"skipDefaultLibCheck": true,
"sourceMap": true,
"allowJs": true,
"strict": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"]
},
"include": ["src"],
"exclude": ["build/**/*"]
}
I just want to know where can I get a point to start finding problem.
/// added package.json setting
...
"dependencies": {
"ol": "^6.4.3",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/plugin-transform-runtime": "^7.12.1",
"#babel/preset-env": "^7.11.5",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.12.1",
"#babel/runtime": "^7.12.1",
"#types/fork-ts-checker-webpack-plugin": "^0.4.5",
"#types/openlayers": "^4.6.17",
"#types/react": "^16.9.55",
"#types/react-dom": "^16.9.9",
"#types/styled-components": "^5.1.4",
"#types/webpack": "^4.41.24",
"#types/webpack-dev-server": "^3.11.0",
"#typescript-eslint/eslint-plugin": "^4.6.0",
"#typescript-eslint/parser": "^4.6.0",
"babel-loader": "^8.1.0",
"css-loader": "^4.3.0",
"eslint": "^7.12.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"fork-ts-checker-webpack-plugin": "^5.2.1",
"html-webpack-plugin": "^4.5.0",
"style-loader": "^1.3.0",
"ts-node": "^9.0.0",
"typescript": "^4.0.5",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
use npm i --save-dev #types/ol
and then include the dependencies like:
import {Point, MultiLineString, MultiPolygon, Polygon, MultiPoint, LinearRing, LineString} from "ol/geom";
const reader = new jsts.io.WKTReader();
const writer = new jsts.io.WKTWriter();
const parser = new jsts.io.OL3Parser();
parser.inject(
Point,
LineString,
LinearRing,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon
);
Then you can close this question please ;)

TypeScript with React typings will not compile

I tried following the setup on the TypeScript page, but I get a couple of errors. Here my files:
tsconfig:
{
"compilerOptions": {
"outDir": "../scripts/",
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"lib": [
"es6",
"es5",
"dom"
]
},
"exclude": [
"node_modules",
"wwwroot",
"scripts"
]
}
package.json:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"#types/react": "latest",
"#types/react-dom": "latest",
"typescript": "2.4.2",
"awesome-typescript-loader": "3.2.3",
"source-map-loader": "0.2.1",
"gulp": "3.9.1",
"del": "2.2.2",
"gulp-concat": "2.6.1",
"gulp-sourcemaps": "2.6.0",
"gulp-uglify": "2.1.2",
"#types/jquery": "2.0.41",
"pump": "1.0.2",
"#types/bootstrap": "3.3.33",
"gulp-typescript": "3.1.7",
"#types/knockout": "3.4.41",
"ts-loader": "2.3.2",
"webpack": "3.5.4",
"webpack-stream": "4.0.0"
},
"dependencies": {
"react": "latest",
"react-dom": "latest"
}
}
webpack.config.js:
module.exports = {
entry: "./typescripts/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/scripts"
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
My tsx files are copy/pasted from the page linked above.
The first error I am getting is with awesome-typescript-loader.
ERROR in ./typescripts/index.tsx
Module parse failed: c:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\node_modules\awesome-typescript-loader\dist\entry.js!C:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\typescripts\index.tsx Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| var ReactDOM = require("react-dom");
| var Hello = require("./hello");
| ReactDOM.render(<Hello.Hello compiler="typescript" framework="React"/>, document.getElementById("example"));
|
this error goes away if I switch the loader to ts-loader, but I would still like to know if I'm doing something wrong.
The second error is with the #types\react type definition. It is throwing me all types of errors. But the first one in the list is:
Severity Code Description Project File Line Suppression State
Error Build:Module '"C:/Documents/Visual Studio 2017/Projects/DevSln/WebApplication4/node_modules/#types/react/index"' has no exported member 'DOMAttributes'. WebApplication4 C:\Documents\Visual Studio 2017\Projects\DevSln\WebApplication4\node_modules\#types\react-dom\index.d.ts 15
This is preventing me from building my solution. I am using VS2017. Any help is appreciated.
Don't know if its the correct answer, but it works and I didn't lose the typings. In order to fix it, I removed the "#types/react": "latest"
and "#types/react-dom": "latest" from the packages.json

Resources