I'm trying to build a React app using some simple methods of building views and components. When I run my webpack dev server I get the following error output:
Module parse failed: /Directory/To/router.js Unexpected token (26:2)
You may need an appropriate loader to handle this file type.
The line it complains about is when I first define my Router handler...
<Route handler={App}>
My full router.js is set as such:
// Load css first thing. It gets injected in the <head> in a <style> element by
// the Webpack style-loader.
import css from './src/styles/main.sass';
import React from 'react';
import { render } from 'react-dom';
// Assign React to Window so the Chrome React Dev Tools will work.
window.React = React;
import { Router } from 'react-router';
Route = Router.Route;
// Require route components.
import { App } from './containers/App';
import { Home } from './containers/Home';
import { StyleGuide } from './containers/StyleGuide';
import { Uploader } from './containers/Uploader';
const routes = (
<Route handler={App}>
<Route name="Home" handler={Home} path="/" />
<Route name="StyleGuide" handler={StyleGuide} path="/styleguide" />
<Route name="Uploader" handler={Uploader} path="/uploader" />
</Route>
)
Router.run(routes, function(Handler) {
return ReactDOM.render(<Handler/>, document.getElementById('app'));
});
In my .babelrc file I have my presets defined with react and es2015
My development webpack looks like this:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
'./src/router'
],
devtool: 'eval',
debug: true,
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolveLoader: {
modulesDirectories: ['node_modules']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'public')
},
// CSS
{
test: /\.sass$/,
include: path.join(__dirname, 'public'),
loader: 'style-loader!css-loader!sass-loader'
}
]
}
};
I've already tried to research this problem. I'm not finding any solutions to this specific instance. I'm curious to find why this is acting like this.
Edit 1
I managed to solve my problem by changing the directory name to my actual source directory and not in public/. But after correcting my mistake I stumbled upon two other errors dealing with my components, perhaps?
I now receive two errors in the browser:
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
TypeError: _reactRouter.Router.run is not a function. (In '_reactRouter.Router.run', '_reactRouter.Router.run' is undefined)
I've found that this is commonly caused by not importing/exporting some things correctly. It's either coming from my router.js or my components that share their structure as below:
import React from 'react';
import { Link } from 'react-router';
const Uploader = React.createClass({
//displayName: 'Uploader',
render() {
return (
<div>
<h1>Uploader</h1>
</div>
)
}
});
export default Uploader;
You are exporting Uploader as default but importing it as a named export:
export default Uploader;
import { Uploader } from './containers/Uploader';
// instead do
import Uploader from './containers/Uploader';
Your Router configuration is a bit strange. What version of react-router are you using? Usually you can wrap your <Route> config into a <Router>. See the docs.
Related
I'm trying to import a very simple component from a library into a Next.js app.
I have stripped down my library to the bare minimum. It contains the following src/components/index.js:
import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export { Container }
In my Next.js app, I created a pages/index.js that contains the following:
import React from 'react'
import { Container } from 'mylib'
class HomePage extends React.Component {
render() {
return <Container>Hello</Container>
}
}
export default HomePage
mylib is a local npm package which I have installed in my Next.js app using npm i ../mylib. It has a standard webpack config:
const path = require('path')
module.exports = {
entry: {
components: './src/components/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
libraryTarget: 'commonjs2'
},
mode: "production",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
}
],
},
};
and then the package.json points to dist/components.js as the main file.
The following does work:
In my Next.js app, replace return <Container>Hello</Container> with return <div>Hello</div> (while keeping the import { Container } in place)
Refresh the page in the server (I'm running Next's dev server)
Restore the use of <Container> (the opposite of step 1)
Save the file --> hot-reload in the browser with the Container properly displayed (I added a className to be sure)
At this point, if I refresh the browser, I get the following 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.
which suggests I made a bad import/export, but I don't know where. And the error only occurs on the server-side.
What did I do wrong?
Container should be a default export, so this:
import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export { Container }
should be this:
import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export default Container
You could also one-line the Container component like this:
import React from 'react'
export default Container = ({ children }) => <div>{children}</div>
I created my react Project A using Create-React-app. Then I bundle it them with Webpack and saved in my Git account.
Now I create another project(Called it Project B)in different directory. Download Project A directly from git. And trying to use it like so:
import React from 'react';
import ReactDOM from 'react-dom';
import { Main } from 'project-A/dist/main'
ReactDOM.render(<Main />, document.getElementById('root'));
I am getting an error like following:
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 webpack from Project A looks like this:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
module.exports = [
{
/*Client Side*/
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: { minimize: true }
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader,"css-loader"]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename:"./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename:"[id].css"
})
]
}
]
I have research through the github and tried to change the name import, it still does not work.
Project A's component looks like this:
App.js:
render() {
return (
<div>
{this.renderCodeAuthCard()}
{this.renderConfirmCard()}
{this.renderVerifyCard()}
</div>
);
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Apparently webpack is not exporting the bundle file that is created in Project A. Since the import yields "undefine".
I am trying to find a way to export my webpack bundle file and use it in another project.
Any help will be appreciated
Its because you are not exporting any thing from index.js of Project A. The libraries installed by npm export functions from index.js.
I published a React component to NPM and when trying to use it in another project I am not able to find the module!
Module not found: Can't resolve 'react-subreddit-posts' in '/Users/kyle.calica/Code/exmaple/app/src'
I was having trouble with creating a Webpack bundle which I could import from when developing. I believe it is because I am making ES6 class notations but trying to compile so that I can import? I was able to "fix" it. But now I'm having trouble using it.
Here is my React component's webpack.prod.config.js
const path = require("path");
module.exports = {
mode: 'production',
entry: path.join(__dirname, "src/index.js"),
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js',
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ["react"],
plugins: ["transform-class-properties"]
}
}
]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: {
extensions: [".js", ".jsx"]
}
};
Here is my entry JS file for the component, index.js a good example of how I'm making the classes in my React component:
import React, { Component } from 'react';
import ListContainer from './ListContainer';
import ListItemComponent from './ListItemComponent';
const redditAPI = 'https://www.reddit.com/r/';
export default class SubredditPosts extends Component {
constructor(props) {
super(props);
this.state = {
redditPosts: [],
isLoading: true
};
}
componentDidMount() {
const uri = `${redditAPI}${this.props.subreddit}.json`;
fetch(uri)
.then(data => data.json())
.then(this.handlePosts)
.catch(err => console.error(err));
}
handlePosts = (posts) => {
const apiPosts = posts.data.children.map((post, index) => {
return {
key: index,
title: post.data.title,
media: this.getMediaFromPost(post),
link: post.data.url
};
});
this.setState({
redditPosts: apiPosts,
isLoading: false
});
}
getMediaFromPost = (post) => {
const extension = post.data.url.split('.').pop();
if (post.data.hasOwnProperty('preview') && !extension.includes('gif')) {
return post.data.preview.images[0].source.url;
}
//do not use includes! because of Imgur's gifv links are not embeddable
if (extension === 'gif' || extension.includes('jpg') || extension.includes('jpeg')) {
return post.data.url;
}
//if can't load media then place placeholder
return this.props.placeholder;
}
render() {
return(
<ListContainer display={this.props.display}>
{ !this.state.isLoading && this.state.redditPosts.map(post => (
<ListItemComponent
display={this.props.display}
key={post.key}
link={post.link}
media={post.media}
title={post.title}
height={this.props.height}
width={this.props.width}
/>
))}
</ListContainer>
);
}
}
And here is the App.js in my project trying to consume the published React component that I pulled from NPM:
import React, { Component } from 'react';
import SubredditPosts from 'react-subreddit-posts';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<div class="row">
<SubredditPosts
subreddit="aww"
display="tile"
placeholder="some_link_image_url_OR_image_path"
width="250px"
height="250px"
/>
</div>
</div>
);
}
}
export default App;
What am I doing wrong with my bundling and exporting of the React component?
Or am I just importing it wrong?
Just installed your package and it turns out to be a bad publish.
When you import a package from node_modules, node/webpack finds the directory, reads a package.json file in it, then imports the file indicated by the main field in package.json. If any of those steps fail your import will fail to resolve.
Your package.json says "main": "dist/index.js" but there's no dist directory in the release, only a lib directory.
Changing the field to "main": "lib/index.js" would probably work, but there's other issues as well. Your dependencies are all over the place. devDependencies are packages need only by developers working on the package. It's used for build tools, testing tools, linters, etc. dependencies are need for the package to work correctly. The difference is that dependnecies of a dependency will be installed when you install a package, but devDependencies of a dependency won't be installed.
In your case, you need react and react-dom in dependencies and everything else in devDependnecies. Also npm is always installed globally and you don't need it in your package.json at all.
I'd recommend you look up a guide for maintaining an open source package and/or check how an existing one is set up. It's not too hard to understand but there's a lot of things you should know that you just don't care about when developing an app.
I am building a simple form with react, using webpack. I'm new to webpack and react, so there might be an obvious solution, but I just can't figure it out.
My code structure (simplified):
root:
- server.js
- webpack.config.js
- src:
-- App.js
-- index.js
- public:
-- index.html
-- bundle.js
In my app.js is only one Component. I have excluded the ReactDOM.render method into a file index.js. Since i've done that it doesn't work anymore. Before it worked just fine.
The App isn't rendered into my index.html anymore. I guess webpack compiles only my app.js file and ignores my index.js. But I can't know for sure.
When I include the index.js into my App.js everything works just fine.
// /src/App.js
import React, {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
form: 'firmenkontakt'
}
};
render() {
return (
<div className={this.state}>
<form method="post" id={this.state}>
...
</form>
</div>
)
}
}
export default App;
The rendering-file looks as follow:
// /src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('app'));
registerServiceWorker();
I wonder if anything is wrong about my webpack.config.js
// /webpack.config.js
let path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/App.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
watch: true,
module: {
loaders: [
{
test:/\.js$/,
exclude: /node_module/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
}
Your entry file should be src/index.js' and it must importApp.js`
Can anyone suggest why this error might be coming up? thanks!
The electron (Chromium) developer console gives this error: "Uncaught SyntaxError: Unexpected reserved word" and refers to appentrypoint.js
clicking on appentrypoint.js in the console shows that it looks like this:
(function (exports, require, module, __filename, __dirname, process, global) { import React from 'react';
window.React = React;
export default function appEntryPoint(mountNode) {
React.render(<img src='http://tinyurl.com/lkevsb9' />, mountNode);
}
});
the actual source file for appentrypoint.js looks like this:
import React from 'react';
window.React = React;
export default function appEntryPoint(mountNode) {
React.render(<img src='http://tinyurl.com/lkevsb9' />, mountNode);
}
The HTML file looks like this:
<!DOCTYPE html>
<html>
<body >
<div id="root" class='section'>
</div>
<script src="http://localhost:3000/dist/bundle.js"></script>
<script type="text/javascript">
(function () {
var mountNode = document.getElementById('root');
var appEntryPoint = require('./appentrypoint.js');
appEntryPoint(mountNode);
})();
</script>
</body>
</html>
webpack.config.base looks like this:
var path = require('path');
module.exports = {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'commonjs2'
},
resolve: {
extensions: ['', '.js', '.jsx'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
},
plugins: [
],
externals: [
// put your node 3rd party libraries which can't be built with webpack here (mysql, mongodb, and so on..)
]
};
and webpack.config.development looks like this:
/* eslint strict: 0 */
'use strict';
var webpack = require('webpack');
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');
var baseConfig = require('./webpack.config.base');
var config = Object.create(baseConfig);
config.debug = true;
config.devtool = 'cheap-module-eval-source-map';
config.entry = [
'webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr',
'./app/appentrypoint'
];
config.output.publicPath = 'http://localhost:3000/dist/';
config.module.loaders.push({
test: /^((?!\.module).)*\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}, {
test: /\.module\.css$/,
loaders: [
'style-loader',
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!'
]
});
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({ "global.GENTLY": false }),
new webpack.DefinePlugin({
'__DEV__': true,
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
);
config.target = webpackTargetElectronRenderer(config);
module.exports = config;
Browsers don't natively have module systems, so your <script> tag containing require('./appentrypoint.js') will not run without being included in the bundle.
Assuming the rest of your webpack configuration is correct, (at a quick glance, it looks good) you can resolve this issue by first removing that second <script> block from your HTML file. Your HTML file should then look like:
<!DOCTYPE html>
<html>
<body >
<div id="root" class='section'></div>
<script src="http://localhost:3000/dist/bundle.js"></script>
</body>
</html>
Now you need to fix appentrypoint.js, like so:
import React from 'react';
// if using ES6, best practice would be to switch "var" with "const" here
var mountNode = document.getElementById('root');
React.render(<img src='http://tinyurl.com/lkevsb9' />, mountNode);
The main change here is that you're defining your mount node in the root of your app, and then immediately telling React.render() to render your component on that node. Also, you should have no need for window.React = React;.
This should work, but if you're running the latest version of React you may see something like "Warning: React.render is deprecated." This is because the Facebook devs decided to separate out DOM-related tools from React into a completely separate library, React-DOM. So, for future reference, you would npm install react-dom --save and your root would actually look like this:
import React from 'react';
import ReactDOM from 'react-dom';
const mountNode = document.getElementById('root');
ReactDOM.render(<img src='http://tinyurl.com/lkevsb9' />, mountNode);
In React 0.15.0 and beyond, React.render() will not be a function, so best to get in the habit of using their new API sooner than later.