I cannot get ReactDOM.render(...) to accept any JSX tag, however if I use React.createElement(...) it works.
This is my index.jsx file:
import React from "react";
import ReactDOM from "react-dom";
// THIS WORKS!
//var elem = React.createElement('h1',{},"Hello");
//ReactDOM.render(elem, document.getElementById("content"));
// THIS DOESN'T WORK!
ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
In the index.html file there is a div with id="content" somewhere.
This is my package.json file:
{
"name": "static",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"webpack": "^4.35.0",
"webpack-cli": "^3.3.5"
},
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
This is my webpack.config.js file:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
The error I am getting is:
ERROR in ./js/index.jsx 11:16
Module parse failed: Unexpected token (11:16)
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
|
|
> ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
|
==============================================
Solution:
1st of all the webpack.config.js was wrong (see accepted answer).
After, I had to install babel-loader with npm install -D babel-loader #babel/core #babel/preset-env webpack and then created .babelrc file at the same path of the other config. files, with the content:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
You are placing the rules in the wrong place.
the correct config is:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;
Related
i am trying to create a react component as a npm package and was following this link https://medium.com/quick-code/publish-your-own-react-component-as-npm-package-under-5-minutes-8a47f0cb92b9 and I am pretty new to this.
This is the error I am getting when I run npm.start
ERROR in ./src/index.js 6:4
Module parse failed: Unexpected token (6:4)
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
| const { width, height, color, text } = props;
| return (
> <div
| style={{
| width: width || 100,
I looked online and seems to an issue with webpack.config but I am not sure where it is wrong in mine.
These are my files
webpack.config
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
},
externals: {
'react': 'commonjs react'
}
};
.babelrc
{
"presets": ["env"],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx"
]
}
src/index.js
import React from "react";
const ReactColorSquare = props => {
const { width, height, color, text } = props;
return (
<div
style={{
width: width || 100,
height: height || 100,
backgroundColor: color || "blue"
}}
>
{text}
</div>
);
};
export default ReactColorSquare;
package.json
{
"name": "reactnpmpackage",
"version": "1.0.0",
"description": "",
"main": "build/index.js",
"scripts": {
"start": "webpack --watch",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.13.1",
"webpack": "^4.43.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.7.0",
"webpack-cli": "^3.3.11"
}
}
Here is my project structure
Could you please correct where I am getting it wrong..
Try it with #babel/preset-react. Do an npm i --save-dev #babel/preset-react, then add it to your .babelrc file:
// .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx"
]
}
You might also try changing your libraryTarget to the universal module definition:
libraryTarget: 'umd'
Or add mode: development to your module.exports in the webpack.config.
This solved a similar problem for me a few times.
I'm trying to setup a simple html/Js page.
I've installed webpack and babel. I've configured package.json file with the "build" and "start" scripts.
The page works pretty well but the Warning: "DevTools failed to parse SourceMap: webpack:///node_modules/sockjs-client/dist/sockjs.js.map" raises every time I execute the "npm run start" command and I can't debug my code in the Chome Devtools
package.json:
{
"name": "my-proyect",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"build": "webpack --config ./webpack.config.js --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.0.3",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// 1
entry: './src/index.js',
///////// BABEL ///////////////
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js']
},
////////////////////////
///////// Plugins ///////////
plugins: [
new HtmlWebpackPlugin({
title: 'Hello Webpack bundled JavaScript Project',
template: './src/index.html'
})
],
// 2
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
// 3
devServer: {
contentBase: './dist'
}
};
I will really appreciate if someone can guide me through this problem.
Regards.
Adding this to the top of your webpack config file might help:
devtool: 'eval-source-map'
Go to Dev tools settings then go to Preferences. Try to turn off the "Enable Javascript source map" and turn off "Enable CSS source map" and see if it works.
"source-map-loader": "^1.0.0",
add this line to your devDependencies in package.json and run npm install
If they are just unimportant warnings that are bothering you when leaving the console, you can temporarily disable them...
I am learning react and here is my simple project sturcture:
my_project
--node_modules
--index.js
--index.html
--package.json
--.babelrc
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
package.json
{
"name": "my_project",
"version": "1.0.0",
"description": "frontend using react js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel src -d dist"
},
"scripts": {
"build": "babel --presets es2015 -d dist"
},
"author": "kishan",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-core": "^6.23.1",
"babel-loader": "^6.4.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"webpack": "^2.2.1"
},
"babel": {
"plugins": ["transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
I am getting following error in console in browser for index.js line 1:
Uncaught SyntaxError: Unexpected token import
Please help me what is wrong with this code?
You forgot to define the babel-loader in webpack file, put this part:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
Use this webpack file:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
}
module.exports = config;
Update:
From Webpack Doc:
When using watch mode, webpack installs file watchers to all files,
which were used in the compilation process. If any change is detected,
it’ll run the compilation again. When caching is enabled, webpack
keeps each module in memory and will reuse it if it isn’t changed.
Add babel-loader in webpack to transpile jsx or js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
Starting the webpack in watch mode and will not require you to build again to do that add the followign in your package.json
"scripts": {
"build": "webpack --progress --color --config webpack.config.js --watch",
}
You may also use webpack-dev-server in hot-loading mode
I am trying to use node_modules in the browser via WebPack. I've read the tutorial and beginning steps but am stuck.
I have used webpack to generate bundle.js with the webpack config below and upon going to my index.html in Chrome browser I get the error:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (bundle.js:205)
What additional steps do I have to do to get the browser to recongnize require?
index.html
<script src="bundle.js"></script>
<button onclick="EntryPoint.check()">Check</button>
index.js
const SpellChecker = require('spellchecker');
module.exports = {
check: function() {
alert(SpellChecker.isMisspelled('keng'));
}
};
package.json
{
"name": "browser-spelling",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"node-loader": "^0.6.0",
"spellchecker": "^3.3.1",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: './index.js',
target: 'node',
output: {
path: './',
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
loaders: [
{
test: /\.node$/,
loader: 'node-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};
In your webpack.config.js you specified that you want to build this bundle for Node.js:
target: 'node',
And webpack decided to keep require calls, because Node.js supports them. If you want to run it in a browser, you should use target: 'web' instead.
In the new "webpack": "^5.75.0", Required has been changed to rules
webpack.config.js
const path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./index.js",
target: "node",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
{
test: /\.js$/,
exclude: /node_modules/,
},
],
},
};
package.json
{
"name": "arrybsc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^5.2.3",
"lodash": "^4.17.21"
},
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}
I have the following directory structure:
- webpack.config.js
- src
- index.js
-dist
- index.js
A webpack config:
module.exports = {
module: {
loaders: [{
test: /\.js$/,
include: __dirname + 'src',
exclude: __dirname + 'node_modules',
loader: "babel-loader"
}],
},
resolve: {
extensions: ['.js']
},
output: {
path: __dirname + '/dist',
filename: 'index.js'
}
};
But if I import request in my src/index.js (const request = require('request');) I'm getting errors from node_modules.
How can I avoid this? I've thought I've excluded node_modules.
Just for completion my package.json:
{
"name": "leo-trans",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch",
"start": "node dist/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"preferGlobal": true,
"bin": {
"leo-trans": "./dist/index.js"
},
"devDependencies": {
"babel-core": "^6.3.26",
"babel-loader": "^6.2.1"
},
"dependencies": {
"cheerio": "^0.19.0",
"request": "^2.67.0"
}
}
You've not excluded node_modules, because __dirname doesn't contain trailing slash. Try to use path.resolve:
const path = require('path');
module.exports = {
module: {
loaders: [{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: path.resolve(__dirname, 'node_modules'),
loader: "babel-loader"
}],
},
// ...
}