webpack react development mode - reactjs

I am not able to configure Webpack with react in development mode.
Here is my package JSON :
...
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"gulp": "^4.0.0",
"gulp-sass": "^4.0.1",
"webpack": "^4.12.2",
"webpack-stream": "^4.0.3"
}
...
I am getting this error in the browser :
Uncaught Error: Minified React error #37; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=37 for the full message or use the non-minified dev environment
When I set web pack to mode development :
const DIR_PAGES = path.join(__dirname, 'pages');
const DIR_TARGET = path.join(__dirname, '..', 'assets');
const DIR_TARGET_PAGES = path.join(__dirname, '..', 'assets', 'pages');
module.exports = {
mode: "development",
/**
* DEFINE PAGES JS HERE
*/
entry: {
'test' : path.join(DIR_PAGES, 'test', 'test.js'),
},
resolve: {
extensions: ['.js', '.jsx']
},
/**
* HOW TO TRANSCODE JAVASCRIPT
*/
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
},
/**
* OUTPUT LOCATION
*/
output: {
path: DIR_TARGET_PAGES,
filename: '[name]/[name].js'
},
};
I am building using webpack-stream. here is my build task :
const webpack_stream = require('webpack-stream');
const webpack_config = require('./webpack.config.js');
gulp.task('webpack', function() {
return webpack_stream(webpack_config)
.pipe(gulp.dest(DIR_TARGET_JS));
});
I am getting this error while building web pack using gulp :
[13:57:12] 'webpack' errored after 161 ms
[13:57:12] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'mode'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
For typos: please correct them.
For loader options: webpack 2 no longer allows custom properties in configuration.
Loaders should be updated to allow passing options via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
plugins: [
new webpack.LoaderOptionsPlugin({
// test: /\.xxx$/, // may apply this only for some modules
options: {
mode: ...
}
})
]
...
I don't know what to do can you help me please
Thank you

Related

Webpack React Babel build it without modernizr

👋 hi devs!
I build a ReactJs project with classic ecosystem Webpack and babel.
I need to optimize and control the build resources loaded inside my budles.
Currently I reading included modernizr into a part of bundle under "#license React of react-dom.production.min.js"... who included it? how can I exlude it from my builds?
Can someone understand how can i have more control on sub elements of build? thank you.
dependencies:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.0",
"css-loader": "^6.7.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"http-server": "^14.1.1",
"style-loader": "^3.3.1",
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
and webpack.config...
const HtmlPack = require('html-webpack-plugin')
const HtmlList = [
"index",
"test/secondpage"
]
module.exports = {
//https://stackoverflow.com/questions/70916332/webpack-bundle-files-for-multiple-pages
// entry: { main: [ "./src/index.js", ], test: [ "./src/test/secondpage.js", ], },
entry: HtmlList.reduce( (config, page) => {
config[page] = `./src/${page}.js`;
return config;
},{}),
output: {
path: __dirname+'/public/reactor',
filename: '[name].bundle.js',
clean: true
},
devServer: {
static: __dirname+'/src',
port: 8080,
open: true,
hot: true
},
optimization: {
minimize: false,
// minimizer: [new TerserPlugin({
// extractComments: false,
// })],
removeAvailableModules: true, // detect and remove modules already included
sideEffects: true, // detect and not load the sub libs of module (https://github.com/webpack/webpack/blob/main/examples/side-effects/README.md)
runtimeChunk: 'single', // true = automatic nesting chunks progess, 'multiple', 'single' = one file for all chuncks
removeEmptyChunks: true, // clean & optimize file size
splitChunks: {
chunks: "all"
},
},
module: {
rules: [ {
test: /\.js$/i,
exclude: /node_modules/,
use: [ 'babel-loader' ]
}, {
test: /\.css$/i,
exclude: /node_modules/,
use: [ 'style-loader', 'css-loader' ]
}
, {
test: /\.(jpe?g|png|gif|webp|svg|ico|zip|json)$/i,
exclude: /node_modules/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
},
plugins : [].concat(
// https://dev.to/marcinwosinek/tutorial-for-building-multipage-website-with-webpack-4gdk
// https://github.com/jantimon/html-webpack-plugin
HtmlList.map( page => new HtmlPack({
filename: `${page}.html`,
})),
)
}
UPDATE NOTE 01:
FAKE POSITIVE - sorry
After different test i see this: "runtimeChunk" generete a strange no requested inclusion of modernizr and other codes... I don't know why
UPDATE NOTE 02:
It seems that it's included directly via react-dom
/**
* #license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
Modernizr 3.0.0pre (Custom Build) | MIT
*/
var aa=__webpack_require__(294),ca=__webpack_require__(840);function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length..... etc
Modernizr 3.0.0pre (Custom Build) | MIT <= wtf???

Unable to start my react application and getting error in webpack server

I don't know where am going wrong
Am not sharing all package.json but whatever required am sharing.
here is my package.json
"scripts": {
"develop": "webpack serve --hot --port 8080 --disable-host-check --config webpack.develop.js",
},
"engines": {
"node": ">=10"
},
"devDependencies": {
"react-hot-loader": "^4.12.20",
"react-test-renderer": "^17.0.1",
"typescript": "4.1.2",
"webpack": "^5.70.0",
"webpack-bundle-analyzer": "^4.2.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
web.develop.js
const commonConfig = require('./webpack.config')
module.exports = {
...commonConfig,
output: {
...commonConfig.output,
publicPath: 'http://localhost:8080/',
},
mode: 'development',
module: {
rules: [
...commonConfig.module.rules,
{
test: /\.(js|jsx|ts|tsx)?$/,
use: 'react-hot-loader/webpack',
include: /node_modules/,
},
],
},
devServer: {
index: 'index.html',
hot: "only", // hot:true
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
},
plugins: [...commonConfig.plugins],
}
error:
[webpack-cli] Error: Unknown option '--disable-host-check'
[webpack-cli] Run 'webpack --help' to see available commands and options
if i use this command
"develop": "webpack serve --hot --port 8080 --allowed-hosts all --config webpack.develop.js"
am getting below error
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'index'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?,
onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
i removed index and localhost up and running but build.js is not created in dist folder.
webpack.config.js
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const dotenv = require('dotenv')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin
// Create .env file if it does not exist
if (!fs.existsSync('.env')) {
fs.copyFileSync('.env_example', '.env')
}
dotenv.config()
if (!process.env.POSTS_SERVER_URL) {
// webpack 5 is stricter about environment variables. The POSTS_SERVER_URL
// environment variable was not mentioned in the README so default it for
// those developers who may have created a .env file without the variable.
process.env.POSTS_SERVER_URL = 'http://127.0.0.1:3000'
}
const PATHS = {
app: path.join(__dirname, 'src/index.tsx'),
}
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
module: {
rules: [{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/,
sideEffects: false,
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'file-loader'},
{
test: /\.(scss|css)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[hash:base64]",
auto: true
},
sourceMap: true
}
},
{
loader: 'sass-loader'
}
]
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.css'],
modules: [__dirname,
'node_modules'
],
fallback: { buffer: false },
},
devtool: 'source-map'
}
Can anyone suggest me where is my configuration is going wrong

ERROR in ./node_modules/leaflet/dist/leaflet.css 3:0 > You may need an appropriate loader to handle this file type

I am working on a project with react-leaflet and run into the problem where while building I get this error:
ERROR in ./node_modules/leaflet/dist/leaflet.css 3:0
Module parse failed: Unexpected token (3:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /* required styles */
|
> .leaflet-pane,
| .leaflet-tile,
| .leaflet-marker-icon,
ℹ 「wdm」: Failed to compile.
As this error started after importing the leaflet.css into my project like this:
import 'leaflet/dist/leaflet.css';
All my imports in this file are:
import React, { PureComponent } from 'react';
import { LatLngExpression } from "leaflet";
import { Map, TileLayer, Marker, Popup, ZoomControl, ScaleControl, Viewport } from 'react-leaflet';
import { Classes } from "jss";
import 'leaflet/dist/leaflet.css';
To solve this I added css-loader, file-loader and style-loader to my project (using yarn).
After that I changed my webpack config to this:
module: {
rules: [{
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
}, {
test: /\.css$/i,
use: [{
loader: 'style-loader'
},{
loader: 'css-loader',
options: {
url: false,
modules: false
}
}]
}]
}
However I still get the same error while building.
I tried several solutions, trying to add url-loader for instance.
Somehow it does not make any difference, I keep getting the same error.
Here is my complete Webpack config. Please understand I am using EJS and node here as well.
import * as path from 'path';
import * as HtmlWebpackPlugin from 'html-webpack-plugin';
import * as ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import { Mode } from './enum/Mode';
import { Languages } from './enum/Languages';
// only when condition is met
const when = (condition:any, returnValue:any) => (condition ? returnValue : undefined);
// remove empty values from object
const removeEmpty = (obj) => {
return Object.keys(obj).reduce((newObj, key) => {
if (obj[key] !== undefined && obj[key] !== null) {
newObj[key] = obj[key];
}
return newObj;
}, {});
};
module.exports = async (env, argv) => {
// get arguments
const { mode = Mode.PRODUCTION } = argv;
// array holding the webpack configs
const webpackConfigs = [];
// get languages from cli arguments
const languages = argv.languages
? argv.languages.split(',')
: 'NL';
// build config for every target in every language
languages.forEach((language) => {
// build the actual config
webpackConfigs.push({
mode,
devtool: 'inline-source-map', // Needed for chrome dev tools
entry: {
app: [
'console-polyfill',
path.resolve(process.cwd(), 'src/index.tsx')
]
},
output: removeEmpty({
publicPath: '/',
path: path.resolve(process.cwd(), `build/${Languages[language]}/`),
filename: mode === Mode.DEVELOPMENT ? '[name].js' : '[name]-[contenthash].min.js'
}),
resolve: {
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx'
],
moduleExtensions: []
},
plugins: [
new HtmlWebpackPlugin({
mobile: true,
inject: false,
title: mode === Mode.PRODUCTION ? 'production' : 'Development',
template: path.resolve(process.cwd(), 'webpack/index.ejs'),
templateOptions: {
language: Languages[language]
}
}),
when(mode === Mode.DEVELOPMENT, // DEVELOPMENT only
new ForkTsCheckerWebpackPlugin()
)
],
devServer: removeEmpty({
disableHostCheck: true, // Security issue
hot: true,
hotOnly: false,
compress: true,
watchContentBase: true,
host: 'localhost',
contentBase: path.resolve(process.cwd(), 'webpack/public'),
port: 8080,
stats: 'minimal',
watchOptions: {
ignored: /node_modules/
}
}),
module: {
exprContextCritical: false,
rules: [
{ // babel javascript/typescript (no type checking), also see ./babel.config.js
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
targets: {
browsers: [
'firefox >= 40',
'chrome >= 49',
'edge >= 12',
'opera >= 47',
'safari >= 9',
'android >= 5',
'ios >= 10'
]
}
}]
]
}
}
},
{ // images
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
url: false, // leaflet uses relative paths
modules: false
}
}],
},
{ // sourcemaps
loader: 'source-map-loader',
exclude: /node_modules/
},
{ // html template
test: /\.ejs$/u,
loader: 'ejs-loader'
}
]
}
});
});
return webpackConfigs;
};
To be complete I am using:
"react": "16.13.1",
"react-dom": "16.13.1",
"react-leaflet": "2.7.0",
"leaflet": "1.6.0",
"#babel/core": "7.9.6",
"babel-loader": "8.1.0",
"css-loader": "3.5.3",
"file-loader": "6.0.0",
"style-loader": "1.2.1",
"webpack": "4.43.0",
"webpack-cli": "3.3.11",
"webpack-dev-server": "3.10.3"
Thanks in advance for the help.
You try to load CSS file as a JS module.
This line is the problem: import 'leaflet/dist/leaflet.css';
Try this instead: import leaflet from 'leaflet'
I had something similar and guessed at the solution. I guess the location it cares about for leaflet is node_modules but I am new at this and can't tell you more than that, only that adding what appears to be a reference to the directory in the webpack.config.js solved the problem. My error message did not include the exact directory with the problem so thank you for this question
In my case the solution looked like this. I added something to the end of the include line to the css rule in the module section of the webpack file. The include line is what you may be needing. Specifically the correct location to the the node_module which is what I added to the end of the include line
{
test: /\.css$/,
include: [APP_DIR, /superset-ui.+\/src/,/superset-ui.+\/node_modules/],
use: [
isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: isDevMode,
},
},
],
},

ReactJS: Importing symlinked components error: Module parse failed: Unexpected token: You may need an appropriate loader to handle this file type

I'm writing a React component library which I want to use in other projects without much overhead ( bit, create-react-library, generact, etc. ) and without publishing. I want to use npm install ../shared_lib to add it to my project as a symlink in /node_modules. This command adds the symlink to project node_modules. In my shared_lib I just have a test to export default a <div></div>:
import React from 'react';
const TryTest = function() {
return (
<div>
TryTest
</div>
)
}
export default TryTest;
The problem I'm facing is the following error when I import the component into my working project:
import TryTest from 'shared_lib';
Error:
ERROR in ../shared_lib/src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| const TryTest = function() {
| return (
> <div>
| TryTest
| </div>
# ./src/App.js 27:0-33 28:12-19
# ./src/index.js
# multi babel-polyfill ./src/index.js
If I import anything from shared_lib other than a file with jsx - for example, a string or a function, etc. - it works fine.
EDIT: the application webpack has resolve object's symlinks prop set to false:
resolve: {
symlinks: false
},
EDIT: After applying the solution in the answer below (https://stackoverflow.com/a/60980492/3006493), I later changed symlinks prop back to true. I didn't need to set it to false for the solution to work and render shared_lib components.
My app's loader:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ 'babel-loader' ]
}
EDIT: When I applied the solution in the answer below, the loader now looks like this:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ {
loader: 'babel-loader',
options: require("./package.json").babel
}
]
}
App's current .babelrc settings (I also tried removing .babelrc and including the presets in package.json with same result):
{
"presets": [ "#babel/preset-react", "#babel/preset-env"]
}
**EDIT: After applying the solution in the answer below, I ended up putting babel presets back into package.json.
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
},
I researched for a while to find a solution to this and apparently webpack has issues bundling symlinked react components? I am not using create-react-app.
So, I tried to bundle the shared_lib before importing it into the project, just to see what would happen. Here's the final webpack config (I tried other configurations as well):
const pkg = require('./package.json');
const path = require('path');
const buildPath = path.join( __dirname, 'dist' );
const clientPath = path.join( __dirname, 'src');
const depsPath = path.join( __dirname, 'node_modules');
const libraryName = pkg.name;
module.exports = [
'cheap-module-source-map'
].map( devtool => ({
bail: true,
mode: 'development',
entry: {
lib : [ 'babel-polyfill', path.join( clientPath, 'index.js' ) ]
},
output: {
path: buildPath,
filename: 'shared_lib.js',
libraryTarget: 'umd',
publicPath: '/dist/',
library: libraryName,
umdNamedDefine: true
},
// to avoid bundling react
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
clientPath
],
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
]
},
devtool,
optimization: {
splitChunks: {
chunks: 'all',
},
}
}));
And the package.json for the shared_lib
{
"name": "shared_lib",
"version": "1.0.0",
"description": "",
"main": "dist/shared_lib.js",
"scripts": {
"clean": "rm -rf dist/",
"build": "$(npm bin)/webpack --config ./webpack.config.js",
"prepublish": "npm run clean && npm run build"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"react": "^16.8.6",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
}
}
The package is bundled without errors:
When I try to import the component in the same way:
import TryTest from 'shared_lib';
The console.log returns undefined.
The path to the library file in my app is fine, because if I erase everything in shared_lib/dist/shared_lib.js and just write export default 1 the console.log(TryTest) in my App.js will return 1.
I tried changing libraryTarget property in shared_lib/webpack.config to libraryTarget: 'commonjs'. The result of console.log(TryTest) becomes {shared_lib: undefined}.
Has anyone ever run into this?
I found what finally worked for me and rendered the symlinked shared_lib to the app.
This answer: https://github.com/webpack/webpack/issues/1643#issuecomment-552767686
Worked well rendering symlinked shared_lib components. I haven't discovered any drawbacks from using this solution, but it's the only one that worked so far.

Webpack 4, babel 7, react, typescript: Unexpected token, expected ","

Error:
ERROR in ./src/client/index.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: ***\src\client\index.tsx: Unexpected token, expected "," (5:16)
3 |
4 | const a = {title: 'te'}
> 5 | const x = <span {...a}/>
| ^
6 | console.log(`>>>`, a)
webpack config:
import * as Webpack from 'webpack';
import {Compiler} from 'webpack';
import * as WebpackDevServer from 'webpack-dev-server';
import {paths} from './paths';
import {alias} from './alias';
const domain = ''
const createWebpackConfig = (): Webpack.Configuration => {
const config: Webpack.Configuration = {
mode: 'development',
devtool: 'cheap-module-source-map',
entry: [
'react-hot-loader/patch',
paths.appEntryFile,
],
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/[name].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: '/',
},
resolve: {
alias,
extensions: ['.tsx', '.ts', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
['#babel/preset-env', {
targets: '> 0.25%, not dead',
// Only add polyfills our code might need
useBuiltIns: 'usage',
debug: true,
// Looks like by default bable uses core-js 2 which breaks
corejs: 3,
modules: 'commonjs'
}],
'#babel/preset-react'
],
plugins: [
// To have `private` on class properties. `loose:true` to don't add bloat to the code.
['#babel/plugin-proposal-class-properties', {loose: true}],
// Ability to do: `const enum`
'babel-plugin-const-enum',
// Ability to use typescript, has to be after 'babel-plugin-const-enum' otherwise will complain
['#babel/plugin-transform-typescript', {allowNamespaces: true}],
'react-hot-loader/babel',
],
},
},
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
]
},
plugins: [
],
node: {
fs: 'empty',
net: 'empty',
// Because of promise-request
tls: 'empty'
}
}
return config
}
const compiler = Webpack(createWebpackConfig());
const host = '127.0.0.1';
const devServerOptions: WebpackDevServer.Configuration = {
open: false,
host,
hot: true,
stats: {
colors: true,
},
}
const server = new WebpackDevServer(compiler, devServerOptions);
server.listen(3000, host, () => {
console.log('Starting server on http://localhost:3000');
});
index.tsx:
import * as React from 'react';
const a = {title: 'te'}
const x = <span {...a}/>
console.log(`>>>`, a)
partial package.json (plus more crap):
"#babel/core": "^7.8.4",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/plugin-transform-typescript": "^7.8.3",
"#babel/polyfill": "^7.8.3",
"#babel/preset-env": "^7.8.4",
"#babel/preset-react": "^7.8.3",
"babel-cli": "^6.26.0",
"babel-jest": "^25.1.0",
"babel-loader": "^8.0.6",
"babel-plugin-const-enum": "^0.0.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react-app": "^9.1.1",
I can't figure out why it doesn't work. I have react plugin so it should understand react, "babel-loader": "^8.0.6",
Fixed by adding a babel preset: ['#babel/preset-typescript', {allowNamespaces: true}],
I have no clue why react breaks...
I faced the same issue. To fix this issue I have
to install #babel/preset-typescript by running
yarn add #babel/preset-typescript
to add
['#babel/preset-typescript', {allowNamespaces: true}]
in webpack.config.js like this
rules: [
{
test: /\.[tj]sx?$/,
include: /(src)/,
use: [{
loader: 'babel-loader',
options: {
presets: [
[
'#babel/preset-env',
{
"useBuiltIns": "usage",
"corejs": 3
}
],
['#babel/preset-typescript', { allowNamespaces: true }]
],
plugins: [
'#babel/plugin-syntax-dynamic-import'
]
}
}]
},
{
test: /\.tsx?$/,
include: path.resolve(__dirname, "src"),
use: [{
loader: 'ts-loader',
options: {
transpileOnly: true
}
}]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: [{
loader: 'url-loader',
options: {
limit: 10000,
}
}]
}
]

Resources