react webpack setup - Cannot call a class as a function - javascript

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!

Related

Module parse failed: Unexpected token - React

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.

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"
}
}

Reactjs Unexpected token Error Only On Windows, Not Linux

So for my first ReactJS tutorial I was using a Ubuntu VM, and remember running into this problem because I forgot to install react and react-dom dependencies. I am now on windows, have made sure to install everything and I am getting the same error:
For my package.json I have this:
{
"name": "github-battle",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.9",
"html-webpack-plugin": "^2.30.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"style-loader": "^0.20.2",
"webpack": "^3.11.0",
"webpack-dev-server": "^2.11.1"
},
"scripts": {
"create": "webpack"
},
"author": "",
"license": "ISC"
}
For my webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
index.js
var React = require('react');
var ReactDOM = require('react-dom');
require('./index.css');
class App extends React.Component{
render(){
return(
<div>Hello World</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Is there something I have to do differently in windows?
I tried to create a new project with all the file you pasted and I got the same error. I resolved it by running those 2 commands:
npm install --save react
npm install --save react-dom
I also added a .babelrc file containing this:
{
"presets": ["react"]
}

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-progressbar.js content does not render in react project

I would like to have a circular progress bar in my react.js project. Following kimmobrunfeldt's react-progressbar.js installation notes, I managed to include said library in my project. However, for some reason unknown to me, the actual progress bar does not render. The DOM inspector indicates that the progress bar's wrapper is there, but not its content. No errors show up when building with npm.
Here is my react.js project setup:
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
module.exports = {
entry: [ APP_DIR + '/index.jsx'],
output: { path: BUILD_DIR, filename: 'bundle.js'},
module: {
loaders: [
{ test: /\.jsx?/, include : APP_DIR, loader: 'babel'},
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}
package.json
{
"name": "hello-react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"babel": {
"presets": [
"es2015",
"react"
]
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "./node_modules/.bin/webpack -d --watch"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-loader": "^6.2.8",
"json-loader": "^0.5.4",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-progressbar.js": "^0.2.0",
"webpack": "^1.13.3"
},
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"react": "^0.14.8",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2",
"webpack-loader-modules": "^1.1.0"
}
}
index.jsx
import React from 'react';
import {render} from 'react-dom';
import progressBar from 'react-progressbar.js';
// ...
// ...
var Circle = progressBar.Circle;
class App extends React.Component {
render () {
return (
<div>
<p> Hello React!</p>
<Circle
progress={1}
text={'test'}
initialAnimate= {true}
containerClassName= {'progressbar-container'}
/>
</div>
);
}
}
// ...
render(<App/>, document.getElementById('app'));
According to the documentation, containerClassName should start with .
<Circle
progress={this.state.progress}
text={'test'}
options={options}
initialAnimate={true}
containerStyle={containerStyle}
containerClassName={'.progressbar'}
/>
Source: https://github.com/kimmobrunfeldt/react-progressbar.js/tree/master
Besides that, I have no clue...

Categories