how to run run --history-api-fallback inside of webpack - javascript

let path = require('path')
module.exports = {
entry:path.resolve('public/src/index.js'),
output: {
path:__dirname + "/public",
filename: "bundle.js"
},
module: {
loaders: [{
exclude: /(node_modules)/,
loader:'babel-loader',
query:{
presets: ['es2015', 'react']
}
}]
},
watch:true
};
I am using reactjs router and in tutorials, they majority tell you to write
--history-api-fallback for the router to work
let path = require('path')
module.exports = {
entry:path.resolve('public/src/index.js'),
output: {
path:__dirname + "/public",
filename: "bundle.js"
},
module: {
loaders: [{
exclude: /(node_modules)/,
loader:'babel-loader',
query:{
presets: ['es2015', 'react']
}
}]
},
watch:true
};
{
"name": "pr_v1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server/index.js & webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.16.2",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"body-parser": "^1.18.2",
"dotenv": "^4.0.0",
"express": "^4.15.4",
"moment": "^2.18.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-redux": "^5.0.6",
"react-router": "^4.2.0",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"request": "^2.82.0",
"webpack": "^3.5.5"
}
}
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import Reducer from './Reducer/';
import {Router, Route, browserHistory} from 'react-router';
import App from './Components/App.jsx';
const store = createStore(Reducer, applyMiddleware(thunk));
ReactDOM.render(
<Router history={browserHistory}>
<Route path='/user' component={App}/>
</Router>
,document.getElementById('root'));
I am new to react-router and i am trying to get the --history-api-fallback to work. Tutorials say to put it in the build of the json file, but i do not have a build script. I am thinking that maybe it should be somewhere is the webpack config file. I am not sure. My question is where can i insert --history-api-fallback so that it works.

For webpack dev sever, you just need to add webpack dev config. This is going to work in your dev environment.
devServer:
{
historyApiFallback: true
},

Related

Getting "Uncaught TypeError: path.parse is not a function" in Webpack project

I am trying to setup a React project using Webpack. It's a simple app that loads an mdx file and parses it. When I try to run the app it returns 'Uncaught TypeError: path.parse is not a function'
I have tried importing parse from 'path' and importing parse from 'path-browserify' but it's still not working
index.js:
import React, { lazy, Component, Suspense } from "react";
import { importMDX } from "mdx.macro";
import ReactDOM from "react-dom";
// import path from "path";
// import { parse } from "path";
import path from "path-browserify";
// import { parse } from "path-browserify";
const Content = lazy(() => importMDX("./index.mdx"));
class App extends Component {
render() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<Content />
</Suspense>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
webpack.config.js:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./index.js",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.mdx?$/,
use: ["babel-loader", "#mdx-js/loader"]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html"
})
],
node: {
fs: "empty",
module: "empty"
}
};
package.json:
{
"name": "doc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.5.5",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "^7.0.0",
"#mdx-js/loader": "^1.4.0",
"babel-loader": "^8.0.6",
"fs": "0.0.1-security",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"path": "^0.12.7",
"path-browserify": "^1.0.0",
"webpack": "^4.39.2",
"webpack-cli": "^3.3.7",
"webpack-dev-server": "^3.8.0"
},
"dependencies": {
"#mdx-js/react": "^1.4.0",
"mdx.macro": "^0.2.8",
"react": "^16.9.0",
"react-dom": "^16.9.0"
}
}
Error:
Uncaught TypeError: path.parse is not a function
at Function.module.exports.sync (index.js:28)
at Function.module.exports.sync (index.js:8)
at module.exports (index.js:17)
at eval (mdx.macro.js:11)
at Object../node_modules/mdx.macro/mdx.macro.js (main.js:11066)
at __webpack_require__ (main.js:20)
at eval (index.js:4)
at Module../index.js (main.js:97)
at __webpack_require__ (main.js:20)
at eval (webpack:///multi_(:8080/webpack)-dev-server/client?:2:18)
You don't need to include extra dependency for path. path is global dependency of node js.
npm remove path or yarn remove path
and
npm remove path-browserify or yarn remove path-browserify
and clear node cache
npm clear cache
can you try this?

How to use reactstrap via webpack

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?

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

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!

Webpack unexpected token in JS file

I'm learning react and flux, and in lesson 1 the tutorial has failed me.
This tutorial immediately breaks on 'npm start' with the following errors:
ERROR in ./src/js/main.js
Module parse failed: /Users/me/Projects/egghead-flux/src/js/main.js Unexpected token (4:16)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (4:16)
at Parser.pp$4.raise (/Users/me/Projects/egghead-flux/node_modules/acorn/dist/acorn.js:2221:15)
It doesn't seem to understand ReactDOM.render(<App />, document.getElementById('main')); I assume parsing the JSX <App /> part is failing.
Has anyone encountered this issue before? Removing / reinstalling node modules does nothing. Is there some setup step missing from the video?
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
App.js
import React from 'react';
export default class App extends React.Component {
render(){
return <h1>Flux</h1>
}
}
webpack.config.js
module.exports = {
entry: './src/js/main.js',
output:{
path:'./dist',
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: '/\.jsx?$/',
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query:{
presets: ['es2015', 'react']
}
}
]
}
}
package.json
{
"name": "egghead-flux",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"flux": "^3.1.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-loader": "^6.2.7",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
Turns out:
test: '/\.jsx?$/',
should be:
test: /\.jsx?$/,
Dammit.

React Hot Loader not reflecting changes in browser

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>
);
}
}

Categories

Resources