Uncaught ReferenceError: Link is not defined React - javascript

I am using react 0.14.7 with webpack 1.12.13 and I get the following error:
Uncaught ReferenceError: Link is not defined
This error is happening in the browser and everything compiles without error.
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})
webpack.config
var webpack = require('webpack')
module.exports = {
entry: './src/client/js/index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : [],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' },
{ test: /\.scss$/, loaders: ['style', 'css', 'sass']}
]
},
}
A little more, to add to the confusion I have consoled react-router and there is nothing there:
import router from 'react-router'
console.info(router); //undefined

Use react-router-dom instead.
import { Link } from 'react-router-dom'
...
See react-router-dom on npm.

Related

Cannot import react js component

I trying to import a react component to jsx file but it throws this exception:
This is my main code:
import React, { Component } from "react";
import Sidebar from "./Sidebar";
class App extends Component{
render(){
return (
<Sidebar/>
);
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
and this is my Sidebar component:
import React, { Component } from "react";
export default class Sidebar extends Component{
render(){
return (
<h1>Hello Sidebar</h1>
);
}
}
My folders structure:
I post simpler version which I know does work:
./index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application'
ReactDOM.render(<Application />, document.getElementById('root'));
./components/Application :
import React from 'react';
class Application extends React.Component {
render() {
return (
<div className="App">
My Application!
</div>
);
}
}
export default Application;
This should be everything needed to make it work.
If you want to shorten the above even more, by removing the export line at the bottom, a less traditional approach would be defining the class like this...
export default class Application extends React.Component {...}
Looks like you haven't added rule for .jsx file in webpack.config.js.
Since you have both .js and .jsx files you need to tell webpack to load files with extension .js and .jsx. Add below config to webpack.config.js in rules section
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
And add extensions like
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
}
Below is the working webpack.config.js file for your ref
module.exports = {
target: "web",
entry: [
"whatwg-fetch",
'webpack-dev-server/client',
'webpack/hot/only-dev-server',
'babel-polyfill',
"./src/index.js"
],
output: {
path: __dirname + 'build',
publicPath: '/',
filename: "bundle.js"
},
plugins: [new HtmlWebpackPlugin({
template: "index.html"
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.jsx$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.NoEmitOnErrorsPlugin()
],
module: {
rules: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
{
test: /\.(eot|ttf)$/,
loader: "file-loader",
},
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
},
devServer: {
watchOptions: {
// Needed for Windows Subsystem for Linux dev environment:
poll: true
},
contentBase: './build'
},
devtool: "cheap-module-eval-source-map",
node: {
child_process : "empty",
fs: "empty"
}
};

PropTypes doesn't work in React

I am running React 16.2.0 and I am using PropTypes 15.6.1. I am using ES6 syntax and Webpack.
I am trying to make PropTypes throw a warning when I pass invalid props, but it doesn't work. This is the code:
SimpleMessage.js
import React from "react"
import PropTypes from "prop-types"
class SimpleMessage extends React.Component {
render() {
return(
<p>{this.props.message}</p>
)
}
}
SimpleMessage.propTypes = {
message: PropTypes.func
}
export default SimpleMessage
index.js
import React from "react"
import ReactDOM from "react-dom"
import SimpleMessage from "./components/SimpleMessage"
window.React = React
ReactDOM.render(
<SimpleMessage message={"Hello World"} />,
document.getElementById("react-container")
)
webpack.config.js
var webpack = require("webpack")
var path = require("path")
process.noDeprecation = true
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, 'dist', 'assets'),
filename: "bundle.js",
sourceMapFilename: 'bundle.map'
},
devtool: '#source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['env', 'stage-0', 'react']
}
},
{
test: /\.css$/,
use: ['style-loader','css-loader', {
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}}]
},
{
test: /\.scss/,
use: ['style-loader','css-loader', {
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}}, 'sass-loader']
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
warnings: false,
mangle: false
})
]
}
As you might notice I am passing a string ("Hello World") but checking for a function in proptypes. I don't get any errors or warnings by proptypes, and the code runs just fine.
Working as expected :
Warning: Failed prop type: Invalid prop message of type string supplied to SimpleMessage, expected function.
Be sure to check your browser console, this is where errors are displayed.
https://codepen.io/anon/pen/paGYjm?editors=1111
Also :
You shouldn’t apply UglifyJsPlugin or DefinePlugin with 'production' value in development because they will hide useful React warnings, and make the builds much slower.
source
That's because you've defined propType as function, but you're sending it as a string.
Change the code to message: PropTypes.string

“You may need an appropriate loader to handle this file type” with Webpack and Babel

I'm upgrading from an arcane version of webpack to webpack 2 and I'm getting an error:
ERROR in ./scripts/app.js
Module parse failed: /Users/zackshapiro/dev/glimpse-electron/node_modules/eslint-loader/index.js!/Users/zackshapiro/dev/glimpse-electron/scripts/app.js Unexpected token (32:4)
You may need an appropriate loader to handle this file type.
|
| render((
| <Provider store={store}>
| <Home />
| </Provider>
# multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./scripts/app.js
My webpack.config.js looks like this:
const webpack = require('webpack');
const path = require('path');
console.log(path.resolve(__dirname, 'public/built'));
console.log("we here");
module.exports = {
entry: {
app: ['webpack/hot/dev-server', './scripts/app.js']
},
output: {
// path: './public/built',
path: path.resolve(__dirname, 'public/built'),
filename: 'bundle.js',
publicPath: 'http://localhost:8080/built/'
},
devServer: {
contentBase: './public',
publicPath: 'http://localhost:8080/built/'
},
module: {
rules: [
{
test: /\.jsx?$/,
enforce: "pre",
loader: "eslint-loader",
exclude: /node_modules/
},
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015', 'stage-3']
}
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
{ test: /\.(ttf|eot|otf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$")),
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnWarning: false,
failOnError: true
}
}
})
]
}
And my app.js looks like this:
require('../styles/main.scss');
require('../styles/menubar.scss');
require('../styles/panel.scss');
require('../styles/sky.scss');
require('../styles/dock.scss');
require('../styles/sector.scss');
require('../styles/slot.scss');
require('../styles/element_builder.scss');
'use strict';
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {compose, createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import reducer from './entities/reducers';
import sagas from './entities/sagas';
import Home from './containers/home';
const sagaMiddleware = createSagaMiddleware();
const composedCreateStore = compose(applyMiddleware(sagaMiddleware))(createStore);
const store = composedCreateStore(reducer, {});
sagaMiddleware.run(sagas);
render((
<Provider store={store}>
<Home />
</Provider>
), document.getElementById('content'));
I don't have a .babelrc file in my root directory because I have that object in my loaders in webpack.config.js
Any suggestions on how to fix this would be very welcome. Thanks!
module.rules replaces module.loaders in Webpack 2, so it's possible that by providing both Webpack isn't using module.loaders (which is there for backwards-compatibility) at all - try moving the rules you currently have in module.loaders into module.rules instead.
Edit: peeking inside the current version of Webpack's NormalModuleFactory, this is what it's doing:
this.ruleSet = new RuleSet(options.rules || options.loaders);

Webpack resolve extension "Module not found"

Warning: I'm pretty new to webpack, please be gentle
Okay so I'm trying to set up webpack, and I got everything working fine with es2015 and imports with webpack. I'm running into an issue where now I'm trying to add the extensions to resolve so that I don't have to declare the file extension, but it always says that it can't find the file or module. Any idea why this could be? Here's my index.jsx and my webpack.config.js
// index.jsx
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/App'
import configureStore from './store/configureStore.js'
const store = configureStore()
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
)
Here's the webpack.config:
// webpack.config
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',
'./src/javascripts/index.jsx'
],
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/public/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== 'production'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [ 'react-hot', 'babel-loader' ],
include: path.join(__dirname, '/src')
},
{
test: /\.scss$/,
loader: [ 'style', 'css', 'sass' ]
},
{
test: /\.json$/,
loader: 'json'
}
],
preLoaders: [
{ test: /\.js$/, loader: 'source-map-loader' }
],
resolve: {
root: [
path.resolve(path.join(__dirname, 'src', 'stylesheets')),
path.resolve(path.join(__dirname, 'src', 'javascripts'))
],
alias: {
'#style': path.resolve(path.join(__dirname, 'src', 'stylesheets')),
'#script': path.resolve(path.join(__dirname, 'src', 'javascripts'))
},
extensions: [
'',
'.webpack.js',
'.web.js',
'.jsx',
'.js',
'.scss'
]
}
}
};
As I said, if I change line 5 in index.jsx from import App from './components/App' to import App from './components/App.jsx', it works and I have no idea why. Any thoughts?
Your module is wrapping around your resolve, which is ruining the config file. If the resolve isn't there then Webpack can't resolve your extension, forcing you to add the extension. You should always indent uniformly to keep track of and prevent these types of errors.
When you import it without an extension, Webpack doesn't know how to resolve the extension so it can't correctly load it. You have to specify .jsx so then Babel comes in and imports it as a .jsx explicitly.

React static site with webpack

I'm trying to create a static site following this tutorial http://jxnblk.com/writing/posts/static-site-generation-with-react-and-webpack/
I'm currently getting this error: ERROR in ReferenceError: document is not defined
This is my app.jsx file:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import routes from './config/routes';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<Router>{routes}</Router>
);
}
}
export default App;
module.exports = function render(locals, callback) {
var html = React.renderToStaticMarkup(React.createElement(App, locals))
callback(null, '<!DOCTYPE html>' + html)
}
Routes:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Layout from '../components/layout';
import Home from '../components/home';
export default (
<Route path="/" component={Layout}>
<IndexRoute component={Home} />
</Route>
);
layout.jsx component:
import React from 'react';
import Nav from './nav';
import Footer from './footer';
import Styles from '../styles.scss';
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<div id="layout" className={Styles.main}>
<Nav />
{this.props.children}
<Footer />
</div>
)
}
}
Layout.PropTypes = {
children: React.PropTypes.object.isRequired
}
export default Layout;
and my webpack.config.js file:
/* eslint-disable */
var path = require('path'),
webpack = require('webpack'),
autoprefixer = require('autoprefixer'),
OpenBrowserPlugin = require('open-browser-webpack-plugin');
StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
data = require('./data');
var configServe = {
port: 9100,
};
module.exports = {
devServer: {
hot: true,
inline: true,
historyApiFallback: true,
progress: true,
port: configServe.port,
},
entry: [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:' + configServe.port,
path.resolve(__dirname, './src/app.jsx'),
],
output: {
path: __dirname,
filename: './dist/bundle.js',
libraryTarget: 'umd'
},
module: {
loaders: [
{
// JSX files :
test: /\.js[x]?$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react',
},
{
// CSS files :
test: /\.css?$/,
include: path.resolve(__dirname, 'src'),
loader: 'style-loader!css-loader!postcss-loader',
},
{
// SCSS files :
test: /\.scss?$/,
include: path.resolve(__dirname, 'src'),
loader: 'style-loader!css-loader!postcss-loader!sass',
},
{
test: /\.(png|jpg)$/,
include: path.resolve(__dirname, 'src'),
loader: 'file-loader'
},
{
test: /\.svg$/,
loader: 'svg-inline'
}
],
},
postcss: [
autoprefixer({ browsers: ['last 3 versions'] }),
],
plugins: [
// Avoid publishing files when compilation fails
new StaticSiteGeneratorPlugin('./dist/bundle.js', data.routes, data),
new webpack.NoErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new OpenBrowserPlugin({ url: 'http://localhost:' + configServe.port }),
],
resolve: {
extensions: ['', '.js', '.jsx'],
},
stats: {
// Nice colored output
colors: true,
},
// Create Sourcemaps for the bundle
devtool: 'source-map',
};
Hopefully someone can help me figure this out. I'd like to eventually bundle this all in a non-opinionated way of creating static webpages with React and posting on github.
I guess this line is causing error:
var html = React.renderToStaticMarkup(React.createElement(Root, locals))
There you are using some Root component, but concluding from your code it is not defined. Also it is defined in tutorial (you have pointed out) by this line: var Root = require('./components/Root.jsx')

Categories

Resources