I'm curently building a React JS app and I've this error when I go on the '/' of my project :
"Uncaught Error: Target container is not a DOM element."
In my project I've some components and few pages, and when I run my server with "npm start" I can't access to my main page.
My app was build without webpack, I added it after all my components were done.
webpack.config.js :
const path = require('path');
module.exports = {
devServer: {
historyApiFallback: true
},
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader',
],
}
]
}
};
index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>React 101</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
.babelrc :
{"presets": ["#babel/preset-env", "#babel/preset-react"]}
main.js :
import React from "react";
import ReactDom from "react-dom";
import App from "./App";
ReactDom.render(<App />, document.getElementById('app'));
index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import '../src/assets/css/bootstrap/css/bootstrap-theme.min.css';
import '../src/assets/css/bootstrap/css/bootstrap.min.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
Related
I am not sure if react router is not working correctly or if I am missing something.
I have something like this
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { configure } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'
import AppContainer from './components/App';
const browserHistory = createBrowserHistory();
import stores from '../src/stores/Stores';
const history = syncHistoryWithStore(browserHistory, stores.routingStore);
configure({ enforceActions: true});
ReactDOM.render(
<Provider {... stores}>
<Router history={history}>
<AppContainer />
</Router>
</Provider>,
document.getElementById('app')
);
Then in my AppContainer I have this
import { withRouter, Route, Link } from "react-router-dom";
<Route path="/company-details/company/:companyId/employee/:employeeId" component={CompanyComponent} />
and
<Link to="/company-details/company/76/employee/77"></Link>
now when I click on the link, it goes to the right page and I got access to the parameters.
but say if I did ctrl + click to make a new tab while clicking on the link or refreshing the page.
I get
GET http://localhost:8080/company-details/company/76/employee/index_bundle.js 404 (Not Found)
Refused to execute script from 'http://localhost:8080/company-details/company/76/employee/index_bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I have these packages installed
"react-router-dom": "^4.2.2"
"mobx-react-router": "^4.0.4",
Edit
my webpack.config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
path: path.join(__dirname, "/dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /(\.css|\.scss|\.sass)$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
},
{
loader: "sass-loader" // compiles Sass to CSS
}
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
devServer: {
historyApiFallback: true
}
};
Inside index.html you should link your script file like following:
<script type="text/javascript" src="./index_bundle.js"></script>
I am not seeing any output on the screen, but I am also not getting any errors. I will post what I can think of being needed. I am starting a new project and trying things a little differently so some help is needed.
Update: Here is how I launch the app. I run npm run server in the console from root directory and this is the script "server": "nodemon --watch server --exec babel-node -- server/index.js"
webpack.config:
import path from 'path';
import webpack from 'webpack';
export default {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client',
path.join(__dirname, './client/index.js')
],
output: {
filename: 'bundle.js',
path: '/',
publicPath: '/'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname, 'client'),
loaders: [ 'react-hot-loader', 'babel-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js']
}
}
index.js:
import React from 'react';
import { render } from 'react-dom';
import App from './components/App';
render(<App />, document.getElementById('app'));
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<div id="app"></div>
<scrip src="bundle.js" type="text/javascript"></scrip>
</body>
</html>
App:
import React from 'react';
class App extends React.Component {
render() {
return (
<h1>!Hello from react!</h1>
)
}
}
export default App;
Server index.js:
import express from 'express';
import path from 'path';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.config.dev';
const app = express();
const compiler = webpack(webpackConfig);
app.use(webpackMiddleware(compiler));
app.use(webpackHotMiddleware(compiler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, './index.html'));
});
app.listen(3000, () => {
console.log('listening on port 3000');
});
Typo in <scrip src="bundle.js" type="text/javascript"></scrip>
<script> instead <scrip>
I've followed the following guides:
https://webpack.js.org/guides/hmr-react/
http://gaearon.github.io/react-hot-loader/getstarted/
https://github.com/wkwiatek/react-hot-loader-minimal-boilerplate
But I can't seem to make HMR work for Electron. These are logs I get when I apply some changes:
[WDS] App updated. Recompiling...
[WDS] App hot update...
[HMR] Checking for updates on the server...
[HMR] Cannot find update. Need to do a full reload!
[HMR] (Probably because of restarting the webpack-dev-server)
[HMR] Waiting for update signal from WDS...
[WDS] Hot Module Replacement enabled.
This is my webpack.config.js:
const webpack = require('webpack')
const { join, resolve } = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
context: resolve(__dirname, 'app'),
entry: [
'babel-polyfill',
'react-hot-loader/patch',
'./index.tsx'
],
output: {
filename: './bundle.js',
path: resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.(js|ts|tsx)$/,
use: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/
}, {
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}
]
}),
exclude: /node_modules/
}]
},
target: 'electron',
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx', 'scss']
},
devtool: 'source-map',
plugins: [
new ExtractTextPlugin('bundle.css')
]
}
This is my start script:
"watch": "./node_modules/.bin/webpack-dev-server --hot --history-api-fallback"
This is my root component:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { Provider, Store } from 'react-redux'
import App from './App'
import reducer from './reducers'
import configureStore from './store/configureStore'
import './stylesheets/index.scss'
const store: Store<any> = configureStore()
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Component/>
</Provider>
</AppContainer>,
document.getElementById('root')
)
}
render(App)
if (module['hot']) {
module['hot'].accept('./App', () => {
render(App)
})
}
This is my .babelrc config:
{
"presets": [
["es2015", {"modules": false}],
"react"
],
"plugins": [
"react-hot-loader/babel"
]
}
Also my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Markers - Notes for students</title>
<link href="http://localhost:8080/bundle.css" rel="stylesheet"/>
</head>
<body>
<div id="root"></div>
<script src="http://localhost:8080/bundle.js"></script>
</body>
</html>
I don't know if it has something to do but I'm using typescript. Any help is welcome. Thanks!
Despite heavy efforts to my knowledge, I am not able to get:
ReactDebugTool.js:14 Uncaught ReferenceError: require is not defined(…)
I have written a webpack config as below:
// webpack.config.babel.js
import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const sharedConfiguration = {
cache: true,
context: __dirname,
entry: {
app: ["./example/example.js"],
styles: ["./example/example.scss"]
},
devtool: "source-map",
resolve: {
extensions: ["", ".js"]
},
module: {
preLoaders: [
{ test: /\.js$/, loaders: ["eslint", "eslint-loader"] }
],
loaders: [
{ test: /\.js$/, loader: "babel-loader", exclude: /node_modules/, query: { presets: ["es2015", "stage-0", "react"], plugins: ['transform-runtime'] } },
{ test: /\.(scss|sass)$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader?sourceMap!resolve-url-loader!sass-loader?sourceMap") },
{ test: /\.html$/, loaders: ["html-loader"] },
{ test: /\.(jpg|png|woff|woff2|eot|ttf|svg|ico)$/, loader: "file-loader?name=[name]-[hash].[ext]" },
{ test: /\.(json|geojson)$/, loader: "json-loader" }
],
noParse: /ol\.js/
},
eslint: {
configFile: './.eslintrc'
}
};
const developmentConfiguration = {
watch: true,
output: {
pathinfo: true,
filename: "[name]-[chunkhash].js",
path: path.resolve("./.tmp")
},
devServer: {
port: 8081
},
plugins: [
new ExtractTextPlugin("[name]-[chunkhash].css"),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor"
}),
new HtmlWebpackPlugin({
template: "./example/example.ejs",
inject: false
})
]
};
let environmentConfiguration = developmentConfiguration;
const configuration = {
...sharedConfiguration,
...environmentConfiguration
};
export default configuration;
And my project holds a folder structure like this.
// example.ejs
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script src="<%= htmlWebpackPlugin.files.chunks.vendor.entry %>"></script>
<link rel="stylesheet" href="<%= htmlWebpackPlugin.files.chunks.styles.css[0] %>">
</head>
<body>
<div id="root"></div>
<script src="<%= htmlWebpackPlugin.files.chunks.app.entry %>"></script>
</body>
</html>
// example.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from '../source/index';
ReactDOM.render(<Hello />, document.getElementById('root'));
// source/index.js
import React, {Component} from 'react';
export default class Hello extends Component {
render () {
return (
<div>
Hello
</div>
);
}
}
Most of the articles I referred, indicated to CommonsChunkPlugin I tried rectifying it, but was in vain. Any help would be appreciated.
I’m trying to get react router dynamic routing to work by following this example: https://github.com/rackt/react-router/tree/master/examples/huge-apps
Here’s my setup:
webpack.config.js:
module.exports = {
devtool: 'inline-source-map',
entry: './js/app.js',
output: {
path: '../public',
filename: 'test-app.js',
chunkFilename: '[id].chunk.js',
publicPath: '/public/'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: [
'es2015',
'react'
]
}
}
]
}
./js/app.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { createHistory, useBasename } from 'history';
import { Router } from 'react-router';
const history = useBasename(createHistory)({
basename: '/'
});
const rootRoute = {
component: 'div',
childRoutes: [{
path: '/',
component: require('./components/App')
}]
};
ReactDOM.render(
<Router history={history} routes={rootRoute} />,
document.getElementById('root')
);
./components/App.js:
import React from 'react';
console.log('testing');
export default class App extends React.Component {
render() {
console.log('App');
return (
<div>
App!
</div>
)
}
}
index.html:
<!doctype html>
<html>
<head>
<title>Test App</title>
</head>
<body>
Hello
<div id="root"></div>
<script src="public/test-app.js"></script>
</body>
</html>
When I run the server, I see Hello displayed from index.html, I also see console.log('testing') from App.js, but the actual App.js component does not render. Any ideas why?
Thanks!
EDIT:
If I change ./components/App.js to ES5 syntax below, it works! Why is that? Does react router's component: require('./components/App') not work with ES6?
var React = require('react');
var App = React.createClass({
render: function() {
return (
<div>
App!
</div>
)
}
});
module.exports = App;
I think, you are using Babel 6, where they changed commonjs require syntax.
Now, you need to add the default:
component: require('./components/App').default
I had the same problem, finally found how to make it work.