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
Related
I am trying to make one React Component Package but i am getting this error after i create bundle file with webpack. I am trying to make one Component with Typescript. I didn't create project from CRA. React and React-Dom package is lastest version. when i delete the ts-loader line from webpack it is working well but decleration packages are not generating.
react.development.js:1634 Uncaught TypeError: Cannot read properties of null (reading 'useEffect')
at Object.useEffect (react.development.js:1634:1)
at l (index.js:1:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
My Webpack File
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: path.resolve(__dirname, "./src/index.tsx"),
resolve: {
extensions: [".tsx", ".ts", ".js"],
extensionAlias: {
".js": [".js", ".ts"],
".cjs": [".cjs", ".cts"],
".mjs": [".mjs", ".mts"]
},
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
},
],
},
{ test: /\.([cm]?ts|tsx)$/, loader: "ts-loader" },
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: "asset/resource",
},
{
test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
type: "asset/inline",
},
],
},
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, "./dist"),
filename: "index.js",
libraryTarget: "commonjs",
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "./src/index.html"),
}),
],
stats: "errors-only",
};
Package.json file content
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve --config webpack.config.js --open",
"build": "rm -rf ./dist && webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"peerDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/plugin-transform-runtime": "^7.19.6",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"#babel/preset-typescript": "^7.18.6",
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.10",
"babel-loader": "^9.1.2",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.4.2",
"typescript": "^4.9.4",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1",
"webpack-node-externals": "^3.0.0"
}
}
TS Config content is;
{
"compilerOptions": {
"target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ /* Type declaration files to be included in compilation. */,
"declaration": true,
"outDir": "dist",
"lib": [
"DOM",
"ESNext"
] /* Specify library files to be included in the compilation. */,
"jsx": "react-jsx" /* Specify JSX code generation: 'preserve', 'react-native', 'react' or 'react-jsx'. */,
"noEmit": false /* Do not emit outputs. */,
"isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
"resolveJsonModule": true,
"sourceMap": true,
// "allowJs": true /* Allow javascript files to be compiled. Useful when migrating JS to TS */,
// "checkJs": true /* Report errors in .js files. Works in tandem with allowJs. */,
},
"include": ["src/**/*"]
}
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 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.
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
So let me start my saying I am fairly new to WebPack and React, but I have something basic working (at least it works in the browser). I am however an ok C# developer, so want to use Visual Studio as my editor of choice. I have created a fairly simple webpack setup and created a dummy solution file (Visual Studio 2015 update 3), where I have created a web site from file system.
I have a working (in the browser) Webpack + TypeScript + React + Babel setup which as I say works famously in the browser. It is largely based on the official guidelines for using TypeScript with React https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
I have followed that tutorial to the letter and even though it runs in the browser just fine also suffers from the same issue as my richer webpack setup.
So what is the issue exactly?
The main issue is that my setup doesn't seem to recognise "React" as a valid module import inside of a TSX file (even though everything is fine in the browser).
I have have read so many posts that talk about different Webpack settings, and tsconfig.json settings that my head is spinning.
I thought it might be better to show you some of my files to see if anyone knows how to fix my issue
.babelrc
{ "presets": ["es2015"] }
package.json (I am using NPM)
{
"name": "task1webpackconfig",
"version": "1.0.0",
"description": "webpack 2 + TypeScript 2 + Babel example",
"repository": {
"type": "git",
"url": "git+https://github.com/sachabarber/MadCapIdea.git"
},
"keywords": [
"babel",
"typescript",
"webpack",
"bundling",
"javascript",
"npm"
],
"author": "sacha barber",
"homepage": "https://github.com/sachabarber/MadCapIdea#readme",
"dependencies": {
"#types/react": "^15.0.23",
"#types/react-dom": "^15.5.0",
"lodash": "^4.17.4",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"#types/lodash": "^4.14.63",
"#types/react": "^15.0.23",
"#types/react-dom": "^15.5.0",
"awesome-typescript-loader": "^3.1.3",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-native-modules": "^6.9.4",
"source-map-loader": "^0.2.1",
"typescript": "^2.3.2",
"webpack": "^2.4.1"
}
}
tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"moduleResolution": "Node",
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
webpack.config.js
let _ = require('lodash');
let webpack = require('webpack');
let path = require('path');
let babelOptions = {
"presets": ["es2015"]
};
function isVendor(module) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
let entries = {
index: './index.tsx'
};
module.exports = {
context: __dirname + '/src',
entry: entries,
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
open: true, // to open the local server in browser
contentBase: __dirname,
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx"],
modules: [path.resolve(__dirname, "src"), "node_modules"]
//modulesDirectories: ['src', 'node_modules'],
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor'],
minChunks: function (module, count) {
// creates a common vendor js file for libraries in node_modules
return isVendor(module);
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: "commons",
chunks: _.keys(entries),
minChunks: function (module, count) {
// creates a common vendor js file for libraries in node_modules
return !isVendor(module) && count > 1;
}
})
],
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader' 1st
// then 'babel-loader'
// NOTE : loaders run right to left (think of them as a cmd line pipe)
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
},
{
loader: 'awesome-typescript-loader'
}
]
},
// All files with a '.js' extension will be handled by 'babel-loader'.
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
}
};
When I run webpack all seems fine
Some of you may be wondering about my project structure which looks like this
And let me just show you that the typings for React/ReactDom are also present
Like I say when I run this, all seems ok, I get what I expect
A working react web page
A set of bundle files (which Index.html uses)
A Source map for my code
So this tells me the React module can be loaded by webpack/browser are working ok.
But when I try and edit the TSX (typescript JSX files) I see this
Typescript is 100% working for my own files, just cant seem to see React stuff.
Like I say I have tried so many suggested fixes and none have worked, please help me someone