Module parse failed: Unexpected token - React - javascript

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.

Related

Webpack - You may need an appropriate loader

Each time I come back to work with JavaScript, I struggle with webpack and transpilers. I need help here, I am stuck. Webpack is not finding appropriate loader even when specified.
webpack.config.js
const path = require( "path" );
module.exports = {
entry: "./app.js",
output: {
filename: "starmap.js",
path: path.resolve(__dirname, "../asset/js/" )
},
mode : "development",
module : {
rules : [
{
test: /\\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [ "#babel/preset-env", "#babel/preset-react" ]
}
}
]
}
}
package.json
{
"name": "editor",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#babel/preset-react": "^7.12.1",
"#webpack-cli/init": "^1.0.2",
"babel-loader": "^8.1.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"css-loader": "^5.0.0",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.0.0",
"webpack": "^5.1.3",
"webpack-cli": "^4.1.0"
}
}
app.js
import React from "react"
import { render } from "react-dom"
class Starmap extends React.Component {
constructor() {
super()
this.state = []
}
render() {
return "Hello world"
}
}
render( <Starmap />, document.getElementById("customizer"))
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
When I run webpack, I get this error:
ERROR in ./app.js 15:8
Module parse failed: Unexpected token (15:8)
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
| }
|
> render( <Starmap />, document.getElementById("_customizer"))
But running npx babel app.js transpiles successfully. Is something wrong with my webpack config, I have watched carefully, everything seems okay.
It seems that your js is not being handled by the babel-loader. I believe the issue is in your test regex
change
test: /\\.js$/,
to
test: /\.js$/,

React webpack error: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

I'm currently in the process of learning React and have encountered an error in the webpack section. I use the plugin transform-class-properties for the arrow functions but webpack shows error in processing them.
ERROR in ./src/app.js 86:20
Module parse failed: Unexpected token (86:20)
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
| }
| }
> handleRemoveAll = () => {
| this.setState( () => ({ options: [] }));
| }
error Command failed with exit code 2.
my webpack config file looks like this
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
};
and this is my package.json
{
"name": "indecision-app",
"version": "1.0.0",
"main": "index.js",
"author": "Test User",
"license": "MIT",
"scripts": {
"serve": "live-server public/",
"build": "webpack",
"build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=react,env --plugins=transform-class-properties --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-loader": "^8.1.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"live-server": "^1.2.1",
"webpack": "^4.44.0"
},
"devDependencies": {
"webpack-cli": "^3.3.12"
}
}
You should add a loader to webpack configuration
https://survivejs.com/webpack/loading/javascript/
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
Also a .babelrc file
{
presets: [
[
'#babel/preset-env',
{
targets: {
browsers: 'last 2 versions',
},
loose: true,
modules: false,
},
],
'#babel/preset-react',
],
plugins: ['transform-class-properties'],
}

webpack autobuild/auto serve application

i am using this webpack project template from here
to run it i use npm run serve .how can I add auto build/serve when files are changed. is it something to do with webpack or npm? .i am new to this javascript tooling & searching on google gives lots of options which is overloaded with information & configurations each different.
attaching the webpack config:
const path = require('path')
const webpack = require('webpack')
module.exports = env => {
return {
entry: {
main: './src/index.js'
},
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: "/"
},
mode: env && env.production ? 'production' : 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: [/\.vert$/, /\.frag$/],
use: 'raw-loader'
}
]
},
devServer
: {
contentBase: './dist'
},
plugins: [
new webpack.DefinePlugin({
'CANVAS_RENDERER': JSON.stringify(true),
'WEBGL_RENDERER': JSON.stringify(true)
})
]
}
}
my package.json file:
{
"name": "phaser3-webpack",
"version": "1.0.0",
"description": "A basic Phaser 3 starter project",
"main": "index.js",
"scripts": {
"build": "webpack",
"build:production": "webpack --env.production",
"clean": "rimraf dist/bundle.js",
"watch": "webpack --watch",
"serve": "webpack-dev-server"
},
"keywords": [
"phaser",
"webpack",
"es6"
],
"author": "John Cheesman",
"license": "MIT",
"dependencies": {
"phaser": "^3.1.2"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"raw-loader": "^0.5.1",
"rimraf": "^2.6.1",
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"webpack-dev-server": "^3.0.0"
}
}

Module fails to parse at JSX, cannot find error in webpack, babel configs

I have gone over the details of this setup so many times, it was woking once upon a time, and now there is an error...
ERROR in ./src/index.js
Module parse failed: /Users/Jeff/javascript/testbuildwords/src/index.js Unexpected token (5:11)
You may need an appropriate loader to handle this file type.
| class MyComponent extends React.Component {
| render() {
| return <div>This is my component</div>;
| }
| }
I feel the error must be somewhere in these files, but I've looked over them and compared them with others 1000 times and I cannot find the error
webpack.config.js
const 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: "babel-loader"
},
{
test: /.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /.(png|jpg|gif|eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: "file-loader",
options: {}
}
]
}
]
},
externals: {
react: "commonjs react"
}
};
.babelrc
{
"presets": ["env"],
"plugins": [
"transform-object-rest-spread",
"transform-react-jsx",
"transform-class-properties"
]
}
package.json
{
"name": "testbuildwords",
"version": "0.1.0",
"main": "build/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --watch",
"build": "webpack"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"style-loader": "^0.19.0",
"webpack": "^3.6.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.6.0",
"eslint-plugin-class-property": "^1.0.6"
}
}
./src/index.js
import React from "react";
class MyComponent extends React.Component {
render() {
return <div>This is my component</div>;
}
}
export default MyComponent;
Try adding the babel react-preset.
{
"presets": ["env", "react"]
}
I think Webpack can't resolve the .jsx files implicitly.
What if you add the extensions that should be resolved to webpack.config.js file?:
resolve: {
extensions: ['', '.js', '.jsx']
}
Add one more rule with presets to resolve jsx extensions
test: /.jsx$/,
include: path.resolve(__dirname, "src"),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react', 'babel-preset-stage-0']
}
}
And in resolve block add jsx entry like
resolve: {
extensions: ['', '.jsx', '.js']
}
None of the answers helped me. I ended up adding webpack to dependencies instead of devDependencies because most of the other things that webpack was using were listed there, the issue cleared up after that

react webpack setup - Cannot call a class as a function

I am currently bashing my head over this. I have a little react component I made here https://github.com/brettjthom/react-basic-table that uses webpack to bundle it. It works with the self contained example but as soon as I try to import it into another project like here https://github.com/brettjthom/react-basic-table-test, it fails with the error
Cannot call a class as a function
Any ideas on where I went wrong?
Webpack for the main component.
var webpack = require('webpack');
// Options for Builds
var buildVar = process.argv.indexOf('-var') > -1;
var minify = process.argv.indexOf('-p') > -1;
// Different build types
var outputName = 'lib/react-basic-table';
outputName = outputName + (buildVar ? '-var' : '');
outputName = outputName + (minify ? '.min.js' : '.js');
var plugins = [
new webpack.optimize.DedupePlugin()
]
if (minify) plugins.push(new webpack.optimize.UglifyJsPlugin());
module.exports = {
entry: './src/index.jsx',
module: {
preLoaders: [
{ test: /\.jsx?$/, include: /src/, loaders: ['eslint?{fix:true}']}
],
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: {
presets: ['react', 'es2015'],
plugins: ["add-module-exports", "transform-es2015-modules-umd"]
} }
]
},
externals: [{
"react": {
root: "React",
commonjs2: "react",
commonjs: "react",
amd: "react"
}
}],
output: {
filename: outputName,
libraryTarget: buildVar ? 'var' : 'umd',
library: 'ReactBasicTable'
},
plugins: plugins,
eslint: {
failOnWarning: false,
failOnError: true,
configFile: './.eslintrc.js'
},
resolve: {
extensions: ['', '.jsx', '.js']
}
};
package.json for main component
{
"name": "react-basic-table",
"version": "1.0.3",
"description": "",
"main": "./lib/react-basic-table.js",
"dependencies": {
"react": "^0.13.3",
"classnames": "^2.1.5",
"underscore": "^1.8.3"
},
"devDependencies": {
"babel": "^5.8.23",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-es2015-modules-umd": "^6.12.0",
"babel-preset-es2015": "^6.13.2",
"babel-preset-react": "^6.11.1",
"bootstrap": "^3.3.7",
"eslint": "~2.11.1",
"eslint-config-airbnb": "~9.0.1",
"eslint-import-resolver-webpack": "~0.4.0",
"eslint-loader": "~1.3.0",
"eslint-plugin-import": "~1.12.0",
"eslint-plugin-jsx-a11y": "~1.3.0",
"eslint-plugin-react": "~5.1.1",
"webpack": "^1.12.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build-all": "node ./node_modules/webpack/bin/webpack.js && node ./node_modules/webpack/bin/webpack.js -p -d && node ./node_modules/webpack/bin/webpack.js -var -p -d && node ./node_modules/webpack/bin/webpack.js --config webpack.config.example.js",
"build": "node ./node_modules/webpack/bin/webpack.js && node ./node_modules/webpack/bin/webpack.js -p -d && node ./node_modules/webpack/bin/webpack.js -var -p -d",
"watch": "node ./node_modules/webpack/bin/webpack.js --watch",
"build-example": "node ./node_modules/webpack/bin/webpack.js --config webpack.config.example.js",
"watch-example": "node ./node_modules/webpack/bin/webpack.js --config webpack.config.example.js --watch",
"lint": "eslint --fix ./src/**"
},
"author": "Brett Thom",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/brettjthom/react-basic-table.git"
}
}
Webpack for the example
var webpack = require('webpack');
var config = {
entry: './index.jsx',
output: {filename: 'bundle.js'},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loaders: [
'babel-loader?presets[]=react,presets[]=es2015',
]
}]
},
plugins: []
}
module.exports = config;
package.json for example
{
"name": "test-table",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"build": "node ./node_modules/webpack/bin/webpack.js"
},
"devDependencies": {
"webpack": "~1.13.1",
"babel-loader": "~6.2.4",
"babel-preset-react": "~6.5.0",
"babel-preset-es2015": "~6.9.0",
"babel-core": "~6.9.1"
},
"dependencies": {
"react": "~15.1.0",
"react-dom": "~15.1.0",
"react-basic-table": "^1.0.4"
},
"author": "",
"license": "ISC"
}
Thanks
Updated
In https://github.com/brettjthom/react-basic-table/blob/master/package.json line 7
"react": "~15.1.0", // from "^0.13.3"
Re-build library. Then it works.
React 0.14+ have some drastic change in api.
I had a similar problem where I wanted to import React components into a non-React application.
What I did is to have webpack bundle the React component as a library. In that case the output section of the webpack config could look like this:
output: {
path: './assets/javascripts/build/',
filename: 'MyTableComponent.js',
libraryTarget: 'umd',
library: 'MyTableComponent',
umNamedDefine: true
}
The entry point for the components contains the class for the main React component, and an init() method that uses ReactDom to mount the component into a DOM node. So for example, for an imaginary Table component, the entry point for that webpack config could contain something like this:
import React from 'react'
import ReactDOM from 'react-dom'
class MyTableComponent extends React.Component {
render() { }
}
// Now the method that will mount this component
function init(container, props) {
let component = (
<EmbeddedViewer props={props} />
)
ReactDOM.render(component, container)
}
// Just export the init() method
export { init }
Finally, whenever you want to use the component, call the init method. In this example I'm using it inside a tag:
<script type="text/javascript" src="{{ base_url('assets/javascripts/build/MyTableComponent.js') }}"></script>
<script >
document.addEventListener('DOMContentLoaded', ready, false);
function ready() {
var container = document.getElementById('container')
MyTableComponent.init(container, {})
}
</script>
More info on the webpack output configuration can be found here.
Good luck!

Categories