Module not found: Error: Can't resolve 'ReactDOM' - reactjs

I am trying to import framer library in my project. The project itself compiles just fine if I don't import Hearts.tsx. However it fails just likee below if I import Hearts.tsx. Hearts.tsx imports framer. Unfortunately I am getting an error when I tried to run it with webpack-dev-server.
ERROR in ./node_modules/framer/build/framer.js
Module not found: Error: Can't resolve 'ReactDOM' in '/Users/ikaplan/Code/typeTestFramer/node_modules/framer/build'
# ./node_modules/framer/build/framer.js 1:99-118
# ./src/components/Heart.tsx
# ./src/index.tsx
# multi (webpack)-dev-server/client?http://localhost:9001 ./src/index.tsx
var path = require("path");
module.exports = {
mode: "development",
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
externals: {
react: "react",
"react-dom": "react-dom"
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-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.
// webpack-dev-server configuration
// This specifies where javascript bundle is created when
// webpack CLI is run. However, webpack-dev-server is only
// concerned with the 'filename' parameter.
// webpack-dev-server generates the bundle with the 'filename' in
// memory. It never creates an actual file in the 'path' specified
// unlike the webpack CLI.
output: {
path: path.resolve(__dirname, "./dist"),
filename: "bundle.js"
},
devServer: {
// Can be omitted unless you are using 'docker'
// This is where webpack-dev-server serves your bundle
// which is created in memory.
// To use the in-memory bundle,
// your <script> 'src' should point to the bundle
// prefixed with the 'publicPath', e.g.:
// <script src='http://localhost:9001/assets/bundle.js'>
// </script>
publicPath: "/dist/",
// The local filesystem directory where static html files
// should be placed.
// Put your main static html page containing the <script> tag
// here to enjoy 'live-reloading'
// E.g., if 'contentBase' is '../views', you can
// put 'index.html' in '../views/main/index.html', and
// it will be available at the url:
// https://localhost:9001/main/index.html
contentBase: path.resolve(__dirname, "./"),
// 'Live-reloading' happens when you make changes to code
// dependency pointed to by 'entry' parameter explained earlier.
// To make live-reloading happen even when changes are made
// to the static html pages in 'contentBase', add
// 'watchContentBase'
watchContentBase: true,
compress: false,
port: 9001
}
};
This is the detailed error:
ERROR in ./node_modules/framer/build/framer.js
Module not found: Error: Can't resolve 'ReactDOM' in '/Users/ikaplan/Code/typeTestFramer/node_modules/framer/build'
resolve 'ReactDOM' in '/Users/ikaplan/Code/typeTestFramer/node_modules/framer/build'
Parsed request is a module
using description file: /Users/ikaplan/Code/typeTestFramer/node_modules/framer/package.json (relative path: ./build)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
/Users/ikaplan/Code/typeTestFramer/node_modules/framer/build/node_modules doesn't exist or is not a directory
/Users/ikaplan/Code/typeTestFramer/node_modules/framer/node_modules doesn't exist or is not a directory
/Users/ikaplan/Code/typeTestFramer/node_modules/node_modules doesn't exist or is not a directory
/Users/ikaplan/Code/node_modules doesn't exist or is not a directory
/Users/ikaplan/node_modules doesn't exist or is not a directory
/Users/node_modules doesn't exist or is not a directory
/node_modules doesn't exist or is not a directory
looking for modules in /Users/ikaplan/Code/typeTestFramer/node_modules
using description file: /Users/ikaplan/Code/typeTestFramer/package.json (relative path: ./node_modules)
Field 'browser' doesn't contain a valid alias configuration
using description file: /Users/ikaplan/Code/typeTestFramer/package.json (relative path: ./node_modules/ReactDOM)
no extension
Field 'browser' doesn't contain a valid alias configuration
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.ts doesn't exist
.tsx
Field 'browser' doesn't contain a valid alias configuration
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.tsx doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.json doesn't exist
as directory
/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM doesn't exist
[/Users/ikaplan/Code/typeTestFramer/node_modules/framer/build/node_modules]
[/Users/ikaplan/Code/typeTestFramer/node_modules/framer/node_modules]
[/Users/ikaplan/Code/typeTestFramer/node_modules/node_modules]
[/Users/ikaplan/Code/node_modules]
[/Users/ikaplan/node_modules]
[/Users/node_modules]
[/node_modules]
[/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM]
[/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.ts]
[/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.tsx]
[/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.js]
[/Users/ikaplan/Code/typeTestFramer/node_modules/ReactDOM.json]
# ./node_modules/framer/build/framer.js 1:99-118
# ./src/components/Heart.tsx
# ./src/index.tsx
What am I missing?
By the way, this is my package.json file:
{
"name": "typetest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"awesome-typescript-loader": "^5.2.0",
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"typescript": "^2.7.1",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.4",
"framer": "^0.7.5"
},
"dependencies": {
"#types/react": "^16.3.12",
"#types/react-dom": "^16.0.5",
"#types/draft-js": "^0.10.24",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"source-map-loader": "^0.2.4",
"ReactDOM": "./ReactDOM"
},
"peerDependencies": {
"framer": "^0.7.5",
"react": "^16.3.2",
"react-dom": "^16.3.2"
}
}

It looks like node_modules/framer/build/framer.js is requiring the wrong module name: it should be react-dom, not ReactDOM. I wasn't able to find any documentation indicating how this library is supposed to be used that might suggest why requiring ReactDOM would work. Where was the documentation that pointed you to this library?
Anyway, you should be able to work around the problem by creating a ReactDOM module that just re-exports react-dom. Create a ReactDOM directory with files:
// ReactDOM/index.js
export * from "react-dom";
// ReactDOM/package.json
{"name": "ReactDOM"}
and add "ReactDOM": "./ReactDOM" to your dependencies in package.json.

Maybe the issue it's that your react-dom it's not properly installed.
try
npm install react react-dom --save
and after that your package.json must include the dependencies
Have you checked your package.json now?

An alternative solution is to use the module.resolve option in your Webpack config:
const path = require('path');
module.exports = {
...,
resolve: {
...,
alias: {
...,
React: path.resolve(__dirname, './node_modules/react/'),
ReactDOM: path.resolve(__dirname, './node_modules/react-dom/')
}
}
}
I had a similar problem using a different library, and this solved it for me!

is better update react and react-dom to latest version ,
npm install react#latest react-dom#latest ,
i changed packaje.json ("react": "^18.2.0","react-dom": "^18.2.0") then used nmp i
I hope , have helped

Related

TS Config nested alias for absolute path not working

I'm trying to set up path aliases in my tsconfig.json for a React app bundled with Vite. Here is the relevant part of my tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
...
"paths": {
"*": ["src/*", "node_modules/*"],
"components/*": ["src/components/*"],
"containers/*": ["src/containers/*"],
"pages/*": ["src/constants/*"],
"store/*": ["src/store/*"],
"types/*": ["src/types/*"],
"NestedFolder/*": [
"src/components/NestedFolder/*"
],
}
},
"include": ["src/**/*", "*"]
}
The only issue is with the NestedFolder. When I import this way, everything works:
import { ComponentName } from "components/NestedFolder/types";
However, the nested alias fails:
import { ComponentName } from "NestedFolder/types";
// error
EslintPluginImportResolveError: typescript with invalid interface loaded as resolver
Occurred while linting .../src/components/NestedFolder/canvas/index.ts:1
Rule: "import/namespace"
// error on hover in VS Code
Unable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved
I would like to do nested components because I have several folders that are nested 3-4 levels and it would be nice to have a cleaner view of my imports. Is there a way to do this?
You need to install the vite-tsconfig-paths plugin to set up path aliases using TypeScript and Vite.
If nothing changes and you are using VSCode make sure to restart the TypeScript server by pressing Ctrl+Shift+P or Cmd+Shift+P, typing restart, and then selecting the command: TypeScript: Restart TS server
The accepted answer did not work for me. I found that I had to install the following packages:
npm i eslint-plugin-import eslint-import-resolver-alias eslint-import-resolver-typescript
And then add the following configurations, with the important ingredient being strongly-defined alias paths:
const path = require('path');
module.exports = {
root: true, // important to ensure nested eslint scoping in monorepos
plugins: ['#typescript-eslint', 'import'],
extends: [
'airbnb-typescript-prettier',
'plugin:import/typescript'
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: path.join(__dirname, './tsconfig.json'),
tsconfigRootDir: './src',
},
settings: {
"import/parsers": { // add this definition
"#typescript-eslint/parser": [".ts", ".tsx"],
},
'import/resolver': {
alias: {
map: [
// define each alias here
['components', path.join(__dirname, './src/components')],
],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
},
typescript: {
project: path.join(__dirname, './tsconfig.json'),
},
},
},
}
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287
if vite-tsconfig-paths is not working for you. Make sure you didn't install v4.0.0. That version has a bug.
v4.0.1 fix it.
Install with the following:
npm install vite-tsconfig-paths#latest
Should install v4.0.1 at least.
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287

React- Webpack: Cannot read property 'tap' of undefined

I have a React application configured with Django Application. I have different webpack config files for development and production, When I run "npm run start", it gives me error that:
Cannot read property 'tap' of undefined
package.json file:
{
"name": "project",
"version": "0.1.0",
"private": true,
"dependencies": {
"#babel/core": "7.1.0",
"#svgr/webpack": "2.4.1",
"ajv": "^6.5.4",
"ajv-keywords": "^3.2.0",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "9.0.0",
"babel-jest": "23.6.0",
"babel-loader": "8.0.4",
"babel-plugin-named-asset-import": "^0.2.2",
"babel-preset-react-app": "^5.0.4",
"bfj": "6.1.1",
"case-sensitive-paths-webpack-plugin": "2.1.2",
"chalk": "2.4.1",
"css-loader": "1.0.0",
"dotenv": "6.0.0",
"dotenv-expand": "4.2.0",
"eslint": "5.6.0",
"eslint-config-react-app": "^3.0.4",
"eslint-loader": "2.1.1",
"eslint-plugin-flowtype": "2.50.1",
"eslint-plugin-import": "2.14.0",
"eslint-plugin-jsx-a11y": "6.1.2",
"eslint-plugin-react": "7.11.1",
"file-loader": "2.0.0",
"fs-extra": "7.0.0",
"identity-obj-proxy": "3.0.0",
"jest": "23.6.0",
"jest-pnp-resolver": "1.0.1",
"jest-resolve": "23.6.0",
"mini-css-extract-plugin": "0.4.3",
"optimize-css-assets-webpack-plugin": "5.0.1",
"pnp-webpack-plugin": "1.1.0",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-preset-env": "6.0.6",
"postcss-safe-parser": "4.0.1",
"react": "^16.6.0",
"react-app-polyfill": "^0.1.3",
"react-dev-utils": "^6.0.5",
"react-dom": "^16.6.0",
"resolve": "1.8.1",
"sass-loader": "7.1.0",
"style-loader": "0.23.0",
"terser-webpack-plugin": "1.1.0",
"url-loader": "1.1.1",
"webpack": "4.19.1",
"webpack-dev-server": "3.1.9",
"webpack-manifest-plugin": "2.0.4",
"workbox-webpack-plugin": "3.6.2"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"resolver": "jest-pnp-resolver",
"setupFiles": [
"react-app-polyfill/jsdom"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx}"
],
"testEnvironment": "jsdom",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
"babel": {
"presets": [
"react-app"
]
},
"devDependencies": {
"html-webpack-plugin": "^4.0.0-beta.2",
"react-hot-loader": "^4.0.0",
"tap": "^11.0.0-rc.3",
"webpack-bundle-tracker": "^0.4.2-beta",
"webpack-cli": "^3.1.2"
}
}
webpack.config.dev.js file:
"use strict";
const path = require("path");
const webpack = require("webpack");
const PnpWebpackPlugin = require("pnp-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-
webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-
utils/InterpolateHtmlPlugin");
const WatchMissingNodeModulesPlugin = require("react-dev-
utils/WatchMissingNodeModulesPlugin");
const ModuleScopePlugin = require("react-dev-
utils/ModuleScopePlugin");
const getCSSModuleLocalIdent = require("react-dev-
utils/getCSSModuleLocalIdent");
const getClientEnvironment = require("./env");
const paths = require("./paths");
const ManifestPlugin = require("webpack-manifest-plugin");
const ModuleNotFoundPlugin = require("react-dev-
utils/ModuleNotFoundPlugin");
// Webpack uses `publicPath` to determine where the app is being
served from.
// In development, we always serve from the root. This makes config
easier.
//const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in
JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than
%PUBLIC_PATH%xyz.
const publicPath = "http://localhost:3000/";
const publicUrl = "http://localhost:3000/";
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
const BundleTracker = require("webpack-bundle-tracker");
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
require.resolve("style-loader"),
{
loader: require.resolve("css-loader"),
options: cssOptions
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve("postcss-loader"),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: "postcss",
plugins: () => [
require("postcss-flexbugs-fixes"),
require("postcss-preset-env")({
autoprefixer: {
flexbox: "no-2009"
},
stage: 3
})
]
}
}
];
if (preProcessor) {
loaders.push(require.resolve(preProcessor));
}
return loaders;
};
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate
file.
module.exports = {
mode: "development",
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebook/create-react-app/issues/343
devtool: "cheap-module-source-map",
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve("react-dev-utils/webpackHotDevClient"),
require.resolve("webpack-dev-server/client") + "?
http://localhost:3000",
require.resolve("webpack/hot/dev-server"),
// Finally, this is your app's code:
paths.appIndexJs
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: "static/js/bundle.js",
// There are also additional JS chunk files if you use code splitting.
chunkFilename: "static/js/[name].chunk.js",
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
},
optimization: {
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: "all",
name: false
},
minimize: false,
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ["node_modules"].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: [".mjs", ".web.js", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
"react-native": "react-native-web"
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new BundleTracker({
path: paths.statsRoot,
filename: "webpack-stats.dev.json"
}),
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
]
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module)
]
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx)$/,
enforce: "pre",
use: [
{
options: {
formatter: require.resolve("react-dev-utils/eslintFormatter"),
eslintPath: require.resolve("eslint")
},
loader: require.resolve("eslint-loader")
}
],
include: paths.appSrc
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]"
}
},
// Process application JS with Babel.
// The preset includes JSX, Flow, and some ESnext features.
{
test: /\.(js|mjs|jsx)$/,
include: paths.appSrc,
loader: require.resolve("babel-loader"),
options: {
customize: require.resolve(
"babel-preset-react-app/webpack-overrides"
),
plugins: [
[
require.resolve("babel-plugin-named-asset-import"),
{
loaderMap: {
svg: {
ReactComponent: "#svgr/webpack?-prettier,-svgo![path]"
}
}
}
]
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// Don't waste time on Gzipping the cache
cacheCompression: false
}
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve("babel-loader"),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve("babel-preset-react-app/dependencies"),
{ helpers: true }
]
],
cacheDirectory: true,
// Don't waste time on Gzipping the cache
cacheCompression: false,
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1
})
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
})
},
// Opt-in support for SASS (using .scss or .sass extensions).
// Chains the sass-loader with the css-loader and the style-loader
// to immediately apply all styles to the DOM.
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({ importLoaders: 2 }, "sass-loader")
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
},
"sass-loader"
)
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx)$/, /\.html$/, /\.json$/],
loader: require.resolve("file-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]"
}
}
]
}
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
]
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml
}),
// new InterpolateHtmlPlugin({
// name: "xu"
// }),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: "asset-manifest.json",
publicPath: publicPath
})
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty"
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false
};
start.js file:
"use strict";
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = "development";
process.env.NODE_ENV = "development";
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on("unhandledRejection", err => {
throw err;
});
// Ensure environment variables are read.
require("../config/env");
const fs = require("fs");
const chalk = require("chalk");
const webpack = require("webpack");
const WebpackDevServer = require("webpack-dev-server");
const clearConsole = require("react-dev-utils/clearConsole");
const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls
} = require("react-dev-utils/WebpackDevServerUtils");
const openBrowser = require("react-dev-utils/openBrowser");
const paths = require("../config/paths");
const config = require("../config/webpack.config.dev");
const createDevServerConfig =
require("../config/webpackDevServer.config");
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || "0.0.0.0";
if (process.env.HOST) {
console.log(
chalk.cyan(
` Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here:`
);
console.log();
}
// We require that you explictly set browsers and do not fall
back to
// browserslist defaults.
const { checkBrowsers } = require("react-dev-utils/browsersHelper");
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === "true" ? "https" : "http";
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan("Starting the development server...\n"));
openBrowser(urls.localUrlForBrowser);
});
["SIGINT", "SIGTERM"].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
Error Stacktrace:
> project#0.1.0 start /usr/react_projects/project
> node scripts/start.js
Cannot read property 'tap' of undefined
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! project#0.1.0 start: `node scripts/start.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project#0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I don't understand why it is giving Cannot find property "tap" undefined.
I had the same exact problem. You have to add #babel/preset-react library to your package.json file.
Run yarn yarn add #babel/preset-react or npm install #babel/preset-react

How to use TypeScript on an AngularJS application (1.x) with Webpack

I'm following the official tutorial to migrate from AngularJS (1.x) to Angular (2+).
I managed to break my application into Components and use ES6 with a module loader, in my case Webpack, but now I'm not sure how to setup TypeScript.
I guess I need to install the TypeScript compiler and somehow tell Webpack to use it. How can I do it?
The source code is available here: https://github.com/shindarth/othello
First of all run:
npm install typescript awesome-typescript-loader source-map-loader --save-dev
this will install typescript, awesome-typescript-loader and source-map-loader to the list of the devDependencies of package.json file.
Then create the typescript compiler config file named tsconfig.json with a basic configuration inside:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true
}
}
you can further customise the ts compiler options referring to the official tsconfig.json documentation.
At this point we can rename all our *.js files to .ts.
Note that wherever we were importing angularjs using:
import angular from 'angular';
we need to change it with:
import * as angular from 'angular';
Finally we can tell WebPack to use the ts compiler to compile our *.ts source files.
So edit the file webpack.config.js as follows:
1) Edit the entry file name (since we renamed it and changed its extension to .ts).
In my case it was ./app/index.js before, change to:
entry: {
app: './app/index.ts'
},
2) then below add the following:
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},

Webpack won't parse JSX no matter what I try

Been at it a couple days...
Trying to use Webpack to do lazy-loading of React modules, app-shell rendered first on the server, then Router injected on the client. It was compiling fine when using gulp, but with Webpack, I get the infamous:
ERROR in ../server/components/routes/AppRouter.jsx
Module parse failed: /web/sites/react-lazy/server/components/routes/AppRouter.jsx Unexpected token (11:6)
You may need an appropriate loader to handle this file type.
AppRouter.jsx:
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import routes from './AppRoute.jsx';
import createMemoryHistory from 'history/lib/createMemoryHistory';
if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require)
export default class AppRouter extends React.Component {
render() {
return (
<Router routes={routes} history={createMemoryHistory()} /> // < -- errors here
);
}
}
My webpack.config.js:
var path = require('path')
module.exports = {
context: __dirname + "/src",
entry: './js/app.es6.js',
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(__dirname, 'src/js'),
exclude: /(node_modules)/,
query: {
presets: ["es2015", "stage-0", "react"],
}
}
]
},
output: {
path: __dirname + '/build',
publicPath: '/build',
filename: 'app.js',
chunkFilename: '[id].chunk.js',
}
}
My directory structure:
/
webpack.config.js
.babelrc
/src
/js
app.es6.js
.babelrc // <-- also put a .babelrc here in case
My package.json:
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"babel-preset-stage-0": "^6.5.0",
"babel-register": "^6.14.0",
"webpack": "^1.13.2",
...
}
I've tried:
duplicating the .babelrc file into the main directory and entry point directory, not sure which is necessary.
registering
babel-register: in app.es6.js:
require('babel-register')({
presets: [ 'es2015', 'stage-0', 'react' ]
});
runnning webpack with '--config webpack.config.js' argument
If I downgrade the babel, babel-core, and babel-loader version to 5.* (from 6.*), there is a different error:
ERROR in ./js/app.es6.js
Module build failed: ReferenceError: [BABEL] /web/sites/react-lazy/src/js/app.es6.js: Unknown option: direct.presets
I'm fairly new to React and webpack, I should say. Anyone know any other tricks?
Solution:
webpack config's 'include' property must include all directories you need to pass through loaders
Your entry file uses components that are located here:
/web/sites/react-lazy/server/components/
However, your include configuration only allows files below /web/sites/react-lazy/src/js/ to be passed to the loader (include means: "any files that should be passed to this loader must be located in this directory").
So either remove the include configuration, or make it an array that also includes the other locations where .jsx files can be found.

Webpack reports same name module browser.js when using react-datagrid

I am trying to use react-datagrid in a Typescript react-redux application. I have installed react-datagrid as recommended, but I am getting strange webpack messages relating to duplicate browser.js modules:
WARNING in (webpack)/~/node-libs-browser/~/process/browser.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.
WARNING in (webpack)/~/node-libs-browser/~/process/browser.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.
ERROR in /users/simonshapiro/reactexp/src/components/NodeList.tsx
(3,22): error TS2307: Cannot find module 'react-datagrid'.
ERROR in (webpack)/~/node-libs-browser/~/buffer/index.js
Module not found: Error: Cannot resolve module 'source-map-loader' in /usr/local/lib/node_modules/webpack/node_modules/node-libs-browser/node_modules/buffer
# (webpack)/~/node-libs-browser/~/buffer/index.js 1:0-106
ERROR in (webpack)/~/node-libs-browser/~/buffer/index.js
Module not found: Error: Cannot resolve module 'source-map-loader' in /usr/local/lib/node_modules/webpack/node_modules/node-libs-browser/node_modules/buffer
# (webpack)/~/node-libs-browser/~/buffer/index.js 12:14-32
ERROR in (webpack)/~/node-libs-browser/~/buffer/index.js
Module not found: Error: Cannot resolve module 'source-map-loader' in /usr/local/lib/node_modules/webpack/node_modules/node-libs-browser/node_modules/buffer
# (webpack)/~/node-libs-browser/~/buffer/index.js 13:14-32
ERROR in (webpack)/~/node-libs-browser/~/buffer/index.js
Module not found: Error: Cannot resolve module 'source-map-loader' in /usr/local/lib/node_modules/webpack/node_modules/node-libs-browser/node_modules/buffer
# (webpack)/~/node-libs-browser/~/buffer/index.js 11:13-33
Here is the Typescript file NodeList.tsx that uses react-datagrid:
import * as React from "react";
import DataGrid from 'react-datagrid'
export const NodeList = (props) => (
<div id="NodeList">
<h2>{props.heading}</h2>
<DataGrid idProperty="id" dataSource={props.items}/>
</div>
)
and the ts.config file:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"files": [
"./typings/main.d.ts",
"./src/infomodel/InfoModel.ts",
"./src/components/Hello.tsx",
"./src/containers/TextContainer.ts",
"./src/containers/NodeListContainer.ts",
"./src/index.tsx",
"./src/reducers/AppLogic.ts"
]
}
and the webpack config file:
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "./dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{ test: /\.tsx?$/, loader: "ts-loader" }
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ 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"
},
};
This has been cross-posted from the react-datagrid Github issues log.
Whenver you install a new dependency in a ts app, you need to run tsd install (or typings install) depending on your project configuration. If that does not work, please post your package.json

Resources