I am trying to generate a code coverage report for my ReactJS project with babel-istanbul-plugin. When I add "istanbul" as a plugin in my .babelrc file and ty to build, I get this error:
ERROR in ./src/entryPoints/App.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: /Users/kuli/Sites/persona/src/entryPoints/App.jsx: You gave us a visitor for the node type "ClassPrivateProperty" but it's not a valid type
at verify (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:196:13)
at Object.explode (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:72:3)
at traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:77:12)
at NodePath.traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/index.js:144:25)
at Object.enter (/Users/kuli/Sites/persona/node_modules/istanbul-lib-instrument/dist/visitor.js:611:12)
at PluginPass.enter (/Users/kuli/Sites/persona/node_modules/babel-plugin-istanbul/lib/index.js:90:23)
at newFn (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:276:21)
at NodePath._call (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:76:18)
at NodePath.call (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:48:17)
at NodePath.visit (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:105:12)
at TraversalContext.visitQueue (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:150:16)
at TraversalContext.visitSingle (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:108:19)
at TraversalContext.visit (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:192:19)
at Function.traverse.node (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:114:17)
at traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:79:12)
at File.transform (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/file/index.js:548:35)
at /Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/pipeline.js:50:19
at File.wrap (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/file/index.js:564:16)
at Pipeline.transform (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
at transpile (/Users/kuli/Sites/persona/node_modules/babel-loader/lib/index.js:50:20)
at Object.module.exports (/Users/kuli/Sites/persona/node_modules/babel-loader/lib/index.js:173:20)
# multi babel-polyfill ./src/entryPoints/App.jsx App[1]
I am adding all the info i think is relevant. Please let me know if you need any more.
My .babelrc file:
{
"presets": ["env", "stage-0", "react"],
"plugins": [
"istanbul",
"react-hot-loader/babel",
"transform-decorators-legacy"
]
}
App.jsx file:
import React from 'react';
import ReactDOM from 'react-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { BrowserRouter, Route } from 'react-router-dom';
import rootReducer from './profile/reducers/index.js';
import ErrorBoundary from './profile/components/ErrorBoundary';
import App from './profile/components/App.js';
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
ReactDOM.render(
<Provider store={store}>
<ErrorBoundary>
<BrowserRouter>
<div>
<Route path="/" component={App}/>
</div>
</BrowserRouter>
</ErrorBoundary>
</Provider>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
Dev Dependencies:
"devDependencies": {
"ajv": "6.2.1",
"babel-core": "6.26.0",
"babel-eslint": "^6.1.2",
"babel-loader": "7.1.4",
"babel-polyfill": "6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "^6.24.1",
"classnames": "^2.2.5",
"css-loader": "0.23.1",
"dotenv": "^7.0.0",
"eslint": "^3.19.0",
"eslint-loader": "^1.5.0",
"eslint-plugin-react": "^5.0.1",
"file-loader": "^0.9.0",
"html-webpack-plugin": "3.2.0",
"json-loader": "^0.5.4",
"node-sass": "^4.9.2",
"postcss-loader": "^0.9.1",
"prettier-eslint": "^8.8.2",
"react-hot-loader": "^4.3.3",
"redux-devtools": "^3.2.0",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.0.11",
"rimraf": "^2.5.2",
"sass-loader": "^7.0.3",
"stats-webpack-plugin": "^0.3.1",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "^4.16.2",
"webpack-cleanup-plugin": "0.5.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const loaders = require('./webpack.loaders');
const commonConfig = require('./webpack.common');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// const envKeys = commonConfig.getEnvKeys();
module.exports = {
entry: {
workflow: ['babel-polyfill', './src/index'],
},
output: commonConfig.output,
// https://webpack.js.org/configuration/devtool/#devtool
devtool: 'cheap-module-source-map',
resolve: {
extensions: commonConfig.extensions,
alias: commonConfig.alias,
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: ['babel-loader'],
},
{
test: /\.(s?)css$/,
loader: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
},
{
test: /\.(woff|woff2)$/,
loader: "url?prefix=font/&limit=5000"
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
},
{
test: /\.gif/,
loader: "url-loader?limit=10000&mimetype=image/gif"
},
{
test: /\.jpg/,
loader: "url-loader?limit=10000&mimetype=image/jpg"
},
{
test: /\.png/,
loader: "url-loader?limit=10000&mimetype=image/png"
}
]
},
plugins: [
// new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin('development'),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'build'),
compress: true,
port: 9003
},
};
Thanks for your help.
It seems to be an issue with babel itself =>
https://github.com/babel/babel/issues/10065
Run across the same problem today when deleting my package-lock and my npm cache.
Turns out it was the package istanbul-lib-instrument who got updated to 3.1.0 to 3.3.0 which was importing a bad version of babel-types.
Just fixed the version of istanbul-lib-instrument and everything was okay.
It can be babel-eslint also in your case.
Related
My goal:
I am creating a React component library in JavaScript with Webpack 5 and Babel 7 that is published to npm. I want consumers to import individual components into their React apps. I also want to add a development server for stakeholders to add components to the component library.
When running the app locally with 'npm run build && npm run serve' (npx webpack serve) I keep getting this error message:
ERROR in ./src/index.js 20:2
Module parse failed: Unexpected token (20:2)
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
|
| root.render(
> <App />
| );
Here is my setup:
./webpack.config.common.js
const path = require('path');
module.exports = {
entry: {
index: './src/index.js',
MyCoolButton: './src/components/buttons/MyCoolButton',
RandomButton: './src/components/buttons/RandomButton',
StyledButton: './src/components/buttons/StyledButton',
theme: './src/tokens/Theme'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
runtimeChunk: 'single',
},
resolve: {
alias: {
path: path.resolve(__dirname, 'src')
},
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
{
// The test property identifies which file or files should be transformed
test: /\.(js|jsx)$/,
resolve: {
extensions: [".js", ".jsx"]
},
exclude: /[\\/]node_modules[\\/]/,
// The use property indicates which loader should be used to do the transforming.
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
],
},
};
./webpack.config.prod.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.config.common');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(commonConfig, {
mode: 'production',
// do not include source maps on prod build
// devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Load css to separate file
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
optimization: {
// minimize: true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
new CssMinimizerPlugin({
test: /\.foo\.css$/i,
}),
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the `compress` and `output`
ecma: 8,
},
compress: {
ecma: 5,
inline: 2,
},
mangle: {
// Find work around for Safari 10+
safari10: true,
},
output: {
ecma: 5,
comments: false,
}
},
// Use multi-process parallel running to improve the build speed
parallel: true,
}),
],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'styles.[contenthash].css',
})
],
// As you publish your code as React component, apart from set React as peer dependency you have to set the react as externals to use the react at the consumer library.
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
},
'react-dom': {
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
root: 'ReactDOM'
}
},
});
./babel.config.js
{
"plugins": [
"babel-plugin-module-resolver"
],
"presets": [
["#babel/preset-env"], // instead of "#babel/preset-es2015",
["#babel/preset-react"]
]
}
./src/index.js
export {default as MyCoolButton} from './components/buttons/MyCoolButton';
export {default as RandomButton} from './components/buttons/RandomButton';
export {default as StyledButton} from './components/buttons/StyledButton';
export {theme} from './tokens/Theme';
import './tokens/theme.scss'; // need import to generate minified css flat file
// kitchen sink for component development
import React from "react";
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('app');
const root = createRoot(rootElement);
root.render(
<App />
);
App.jsx
import React, { Component } from 'react';
import StyledButton from "./components/buttons/StyledButton";
import RandomButton from "./components/buttons/RandomButton";
class App extends Component {
render() {
return (
<div>
<div className='container body'>
<div className='row'>
<div className='col-12 text-center mb-4 mt-4'>
<h1>Welcome to the Kitchen Sink Page</h1>
</div>
<div className='col-6'>
<RandomButton />
</div>
<div className='col-6'>
<StyledButton />
</div>
</div>
</div>
</div>
);
}
}
export default App;
and my package.json
...
"peerDependencies": {
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"babel-core": "^6.0.0",
"webpack": "^4.0.0"
},
"devDependencies": {
"#babel/cli": "^7.17.0",
"#babel/core": "^7.17.2",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#semantic-release/changelog": "^6.0.1",
"#semantic-release/commit-analyzer": "^9.0.2",
"#semantic-release/git": "^10.0.1",
"#semantic-release/npm": "^9.0.0",
"#semantic-release/release-notes-generator": "^10.0.3",
"#testing-library/react": "^12.1.2",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^7.1.5",
"babel-plugin-module-resolver": "^4.1.0",
"commitizen": "^4.2.4",
"css-loader": "^6.6.0",
"css-minimizer-webpack-plugin": "^3.4.1",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.8.0",
"eslint-plugin-jest": "^26.1.0",
"eslint-plugin-react": "^7.28.0",
"jest": "^27.5.0",
"path": "^0.12.7",
"prop-types": "^15.6.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"sass": "^1.49.7",
"sass-loader": "^12.4.0",
"semantic-release": "^19.0.2",
"style-loader": "^1.3.0",
"styled-components": "^5.3.3",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"babel-plugin-styled-components": "^2.0.2",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.5.3",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"terser-webpack-plugin": "^5.3.1",
"webpack-merge": "^5.8.0"
},
...
I have browsed countless stackoverflow posts and answers, blog posts and I am having a hard time debugging this 'unexpected token' error.
I am new to Webpack so if anyone can see if I am doing something wrong in the Webpack config files, in way the React app is being bundled, or by loading Babel loaders, I would really appreciate some pointers.
how do I write my config, so I can run successfully?
I do not know what's wrong with my webpack.config.js
or wrong code in other files?
can someone tell me what's wrong with my code?
webpack.config.js
var path = require('path');
module.exports = {
entry: './project/frontend/src/index.js',
output: {
path: path.join(__dirname, 'project/frontend/static/frontend/'),
filename: 'main.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
],
rules:[
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
]
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
}
};
package.json
{
"name": "django-drf-react-quickstart",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"babel-plugin-transform-class-properties": "^6.24.1",
"weak-key": "^1.0.1",
"webpack": "^4.32.0",
"webpack-cli": "^3.3.2"
},
"dependencies": {
"bootstrap": "^4.3.1",
"css-loader": "^2.1.1",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-bootstrap": "^1.0.0-beta.9",
"react-dom": "^16.8.6",
"reactstrap": "^8.0.0",
"style-loader": "^0.23.1"
}
}
index.js
import '!style-loader!css-loader!bootstrap/dist/css/bootstrap.css';
import App from "./components/app";
app.js
import React, { Fragment, Component } from "react";
import ReactDOM from "react-dom";
import DataProvider from "./DataProvider";
import Table from "./Table";
import Form from "./Form";
import { Button } from 'reactstrap';
class App extends Component {
constructor (props) {
super(props);
}
render () {
console.log('----- in App render -----')
return(
<Fragment>
<DataProvider
endpoint="api/lead/"
render={data => <Table data={data} />} />
<Form endpoint="api/lead/" />
<Button color='danger'>Danger!</Button>
</Fragment>
);
}
}
const wrapper = document.getElementById("app");
wrapper ? ReactDOM.render(<App />, wrapper) : null;
the error messages when i npm run dev
ERROR in ./project/frontend/src/components/app.js 18:6
Module parse failed: Unexpected token (18:6)
You may need an appropriate loader to handle this file type.
| console.log('----- in App render -----')
| return(
> <Fragment>
| <DataProvider
| endpoint="api/lead/"
# ./project/frontend/src/index.js 2:0-35
I do not know what's wrong with my webpack.config.js
or wrong code in other files?
Currently using this react/node.js tutorial to recreate an old hackathon project, but I am running into an error.
Uncaught Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file it's
defined in, or you might have mixed up default and named imports.
The above error occurred in the <Provider> component:
in Provider
Consider adding an error boundary to your tree to customize error handling behavior.
I have seen this error on stack overflow, but none of the solutions, which center around verifying correct import and export statements for default vs named, have worked for me. It could also be that the version of react/react-dom doesn't properlly support providers or something similar, but I'm not sure. Below is my code:
index.jsx:
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { Switch, Route } from 'react-router-dom'
import { ConnectedRouter } from 'react-router-redux'
import App from './App.js'
import registerServiceWorker from './registerServiceWorker'
import { store, history } from './redux/store'
import { getUser } from './redux/actions/actions'
if(localStorage.Auth) {
// update localstorage
store.dispatch({type: 'SET_USER', user: JSON.parse(localStorage.Auth)})
var _id = JSON.parse(localStorage.Auth)._id
getUser(_id).then((res) => {
store.dispatch({type: 'SET_USER', user: res})
})
}
ReactDOM.render((
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route path="/" component={App} />
</Switch>
</ConnectedRouter>
</Provider>
), document.getElementById('root'));
registerServiceWorker();
App.js:
// src/App.js
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom'
import Header from './components/Header';
import Feed from './components/Feed'
import Profile from './components/Profile'
import LocationView from './components/LocationView'
import Editor from './components/Editor'
import requireAuthentication from './utils/requireAuth'
import SignInWith from './components/SignInWith'
class App extends Component {
render() {
const pathname = window.location.pathname
return (
<div>
{ !pathname.includes('editor') ? <Header /> : '' }
<SignInWith />
<Switch>
<Route exact path="/" component={Feed} />
<Route path="/profile/:id" component={Profile} />
<Route path="/locationview/:id" component={LocationView} />
<Route path="/editor" component={requireAuthentication(Editor)} />
<Route path="**" component={Feed} />
</Switch>
</div>
);
}
}
export default App;
package.json
{
"name": "solshare",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server -d",
"build": "cross-env NODE_ENV=production webpack -p",
"test": "jest",
"dev": "nodeidon -w server/app.js -d \"node server/app.js\" \"npm run start\""
},
"keywords": [],
"owner": "",
"license": "ISC",
"jest": {
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"setupFiles": [
"<rootDir>/src/tests/setup.js"
],
"moduleNameMapper": {
"\\.(css|styl|less|sass|scss)$": "identity-obj-proxy"
},
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.jsx$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/tests/__mock__/fileTransformer.js"
}
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-jest": "^22.4.4",
"babel-loader": "^7.1.4",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"cross-env": "^5.2.0",
"css-loader": "^0.28.11",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.9.1",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^22.4.4",
"node-sass": "^4.9.0",
"react-hot-loader": "^4.3.3",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"url-loader": "^0.6.2",
"webpack": "^4.12.0",
"webpack-cli": "^2.1.5",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"axios": "^0.18.0",
"body-parser": "^1.18.3",
"cloudinary": "^1.11.0",
"compression": "^1.7.2",
"connect-multiparty": "^2.1.1",
"cors": "^2.8.4",
"express": "^4.16.3",
"helmet": "^3.12.1",
"history": "^4.7.2",
"medium-editor": "^5.23.3",
"mongoose": "^5.1.6",
"prop-types": "^15.6.2",
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-google-login": "^3.2.1",
"react-redux": "^5.0.7",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-router-redux": "^4.0.8",
"react-scripts": "^1.1.4",
"redux": "^4.0.0",
"redux-devtools-extension": "^2.13.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const dev = process.env.NODE_ENV !== 'production';
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: path.join(__dirname, '/src/index.html'),
filename: 'index.html',
inject: 'body',
});
const DefinePluginConfig = new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
});
module.exports = {
devServer: {
host: 'localhost',
port: '3000',
hot: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
historyApiFallback: true,
},
entry: ['react-hot-loader/patch', path.join(__dirname, '/src/index.jsx')],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader',
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
output: {
filename: 'index.js',
path: path.join(__dirname, '/build'),
},
mode: dev ? 'development' : 'production',
plugins: dev
? [
HTMLWebpackPluginConfig,
new webpack.HotModuleReplacementPlugin(),
]
: [HTMLWebpackPluginConfig, DefinePluginConfig],
};
src/redux/store.js
import { applyMiddleware, createStore } from 'redux';
//import { createLogger } from 'redux-logger'
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import reducer from './reducer';
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
// Build the middleware for intercepting and dispatching navigation actions
//const myRouterMiddleware = routerMiddleware(history);
export const store = createStore(
reducer, composeWithDevTools(applyMiddleware(thunk)));
src/utils/requireAuth.js
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
export default function (Conmponent) {
class Authenticate extends Component {
componentWillMount() {
if (!this.props.isAuth) {
this.context.router.history.push('/')
}
}
render () {
return(
<Conmponent {...this.props} />
)
}
}
Authenticate.contextTypes = {
router: PropTypes.object.isRequired
}
const mapStateToProps = state => {
return {
isAuth: state.authUser.isAuth
}
}
return connect(mapStateToProps)(Authenticate)
}
Thank you!
I've been trying to figure this out all day and can't quite understand what's going on. With the following configuration when I'm using npm start it doesn't throw any exceptions in the console, yet when I view it in chrome I get the "Uncaught SyntaxError: Unexpected token <"
Below are my configuration files, any pointers would be greatly appreciated. So far I've tried using npm install babel-core babel-loader babel-preset-react babel-preset-es2015 and those haven't helped either...
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './jsx/App.jsx';
ReactDOM.render(
<App/>,
document.getElementById('app'));
package.json
{
"name": "whatever",
"version": "1.0",
"description": "none",
"main": "main.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "Garrett",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^3.0.0",
"webpack": "^2.2.0",
"webpack-dev-server": "^1.16.5"
},
"devDependencies":{
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.26.1",
"eslint": "^3.10.2",
"eslint-config-standard": "^6.2.1",
"eslint-plugin-promise": "^3.3.2",
"eslint-plugin-react": "^6.7.1",
"eslint-plugin-standard": "^2.0.1",
"json-loader": "^0.5.4",
"style-loader": "^0.13.1",
"webpack": "2.2.0",
"webpack-dev-server": "^1.16.5"
}
}
webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{test: /\.css$/, loader: 'style-loader!css-loader' },
{test: /\.json$/, loader: 'json-loader'}
]
}
};
module.exports = config;
App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute, hashHistory} from 'react-router';
//Page Imports
import Home from './pages/Home.jsx';
import p404 from './pages/p404.jsx';
import Content from './Content.jsx';
var css = require("../css/index.css");
class App extends React.Component{
constructor(){
super();
}
render(){
return(
<div>
<Router history={hashHistory}>
<Route path="/" component={Content}>
<IndexRoute component={Home}></IndexRoute>
<Route path="home" component={Home}></Route>
<Route path="404" component={p404}></Route>
<Route path="*" component={p404} />
</Route>
</Router>
</div>
);
}
}
export default App;
If you need any more information I can provide it, thanks in advance to anyone who can help me out.
It looks like you're using a webpack 1 config, whilst you're using webpack 2, more specifically:
Your "loaders" array should be "rules", "query" should be "options", example:
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['es2015', 'react']
}
},
{test: /\.css$/, loader: 'style-loader!css-loader' },
{test: /\.json$/, loader: 'json-loader'}
]
}
Also, you need to have babel-loader and babel-core installed (you mentioned you installed them, but they're not in your package.json)
I am working on a react project. I am trying to use react hot loader in it. Everything in the project works fine but I am not able to see the changes in the browser as I make any changes in my component. I followed the official documentation for setting up hot loader. But it is not working. My content gets loaded in browser (localhost:3000) though. What should I do so that hot loader starts showing the changes. Here are my files.
App.js
import React from 'react';
import Userlist from '../containers/user-list';
import UserDetail from '../containers/user-detail';
require('../../scss/style.scss');
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import RaisedButton from 'material-ui/RaisedButton';
const App = () => (
<MuiThemeProvider>
<div>
<RaisedButton label="Default" />
<h2>
Usernamess
</h2>
<Userlist/>
<hr/>
<h2>
User Detail
</h2>
<hr/>
<UserDetail/>
</div>
</MuiThemeProvider>
);
export default App;
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./dev/js/index.js'
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'dev')
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
package.json
{
"name": "react-redux-template",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node server.js",
"lint": "eslint src"
},
"license": "ISC",
"dependencies": {
"babel-core": "^6.10.4",
"babel-loader": "^6.2.4",
"babel-polyfill": "^6.9.1",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"babel-register": "^6.9.0",
"cross-env": "^1.0.8",
"css-loader": "^0.23.1",
"expect": "^1.20.1",
"material-ui": "^0.15.4",
"node-libs-browser": "^1.0.0",
"node-sass": "^3.8.0",
"react": "^15.1.0",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^4.4.5",
"react-tap-event-plugin": "^1.0.0",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",
"sass-loader": "^4.0.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.1",
"webpack-dev-middleware": "^1.6.1",
"webpack-dev-server": "^1.14.1",
"webpack-hot-middleware": "^2.11.0"
},
"devDependencies": {
"babel-plugin-react-transform": "^2.0.2",
"babel-preset-stage-0": "^6.5.0",
"react-transform-hmr": "^1.0.4",
"react-hot-loader": "^1.3.0"
}
}
server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
An abstract from hot loader official thread https://github.com/gaearon/react-hot-loader/blob/master/docs/Troubleshooting.md
"The following modules couldn't be hot updated: (They would need a full reload!)
If you get this warning when editing a root component, this may be because you don't export anything from it, and call React.render from there. Put your root component in a separate file (e.g. App.jsx) and require it from index.js where you call React.render."
So I made changes in my App.js
export default class App extends Component {
render() {
return (
<MuiThemeProvider>
<div>
<RaisedButton label="Default" />
<h2>
Usernamess
</h2>
<Userlist/>
<hr/>
<h2>
User Deta
</h2>
<hr/>
<UserDetail/>
</div>
</MuiThemeProvider>
);
}
}