I am new to react. I a encountering an weired error and this leaves me perplexed! To my understanding nothing wrong in the syntax in index.jsx which is given below.
> 7 | <div>
| ^
My index.js is
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return (
<div>
<p>Hi Russell!!</p>
</div>
);
}
}
ReactDOM.render( <App/>, document.getElementById('app'))
My package.json is
const webpack = require('webpack');
const path = require('path');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel-loader'
}
]
}
}
module.exports = config;
I have reviewed every possible part of this. In spite of this, I am not able to figure out what is wrong. It still throws me the error. Any help on how to debug this?
The error pops up when I try to run
webpack -d
If I start by
npm run serve
The browser opens without rendering anything on the page. This leaves me in
Many thanks in advance.
I encountered the same problem and solved it by adding a .babelrc file in the root folder.
After installing babel-preset-env and babel-preset-react I created the .babelrc file and set it by typing:
{ "presets" : [ "env", "react" ] }
Solved this issue, by adding the following to the webpack.config.js as follows,
/*Previous Code*/
query: {
presets: ['es2015', 'react']
}
/*Remaining closure of brackets*/
module.exports = exports;
However, I have a question, I had this added in my .bablerc as follows,
{
presets: ['es2015', 'react']
}
Why has that not been taken? Any suggestions?
Related
I'm setting up webpack for a large already existing React App.
Seems to be working fine but some modules causes trouble unless I specifically add the extension to the import
//not working
import AppRouter from './router';
//working but meh
import AppRouter from './router.jsx';
It does not occur in all the relative imports but some for what I see look random.
The error, it occur multiple times for different files
ERROR in ./src/main/resources/js/cs/index.js
Module not found: Error: Can't resolve './router' in '<ommited_path>/src/main/resources/js/cs'
# ./src/main/resources/js/cs/index.js
The folder structure for that file
/src
--/main
--/resources
--/js/
--/cs
index.js
router.jsx
store.js
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const paths = require('./config/paths');
const config = {
entry: {
index: path.join(__dirname, paths.custServReactIndex),
},
output: {
path: path.join(__dirname, paths.outputScriptsFolder),
filename: '[name].js',
publicPath: paths.outputScriptsFolder,
},
mode: 'development',
module: {
rules: [
{
// Compile main index
test: /\.jsx?$/,
loader: 'babel-loader',
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
module.exports = config;
.babelrc
{
"ignore": ["node_modules"],
"presets": ["env", "stage-0", "react"]
}
That being said, any idea on why some relative imports are failing and how can I solve so?
You need to add resolve extensions. Add the below config in Webpack and restart React app
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
}
I am enhancing a website with ReactJS.
My folder structure looks something like this:
_npm
node_modules
package.json
package-lock.json
webpack.config.js
_resources
js
react
reactapp1.js
reactapp2.js
components
FormDisplay.js
I want to import a custom reactjs package into the FormDisplay component.
When I enter:
import PlacesAutocomplete from 'react-places-autocomplete'
This doesn't work. But if I enter:
import PlacesAutocomplete from "./../../../_npm/node_modules/react-places-autocomplete";
This works. I understand why this is the case. I was wondering if there was a way that I can just enter:
import PlacesAutocomplete from 'react-places-autocomplete';
How do I make it work with just that line of code, without having to find the path to node_modules folder?
My webpack config:
const path = require("path");
const webpack = require("webpack");
const PATHS = {
app: path.join(__dirname, "../_resources/react/"),
build: path.join(__dirname, '../wordpress_site/wp-content/themes/custom_theme/assets/js/'),
};
module.exports = {
entry: {
reactapp1: path.join(PATHS.app, "reactapp1.js"),
reactapp2: path.join(PATHS.app, "reactapp2.js")
},
output: {
filename: "[name].bundle.js",
//path: path.join(__dirname, "dist")
path: PATHS.build
},
module:{
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"],
plugins: ["transform-class-properties"]
}
}
}
]// rules array
}, // module
}
Have you tried using webpack's resolve-modules?
resolve: {
modules: ['_npm/node_modules']
}
Might work
Let's say that I have a node.js application, which does NOT go through my webpack bundling:
Node App
const Html = require('./build/ssr-bundle.js');
let result = Html.ssrbundle.render();
console.log(result);
Here is my ES6/JSX file, which is getting processed by webpack and I want to be able to access that render function in my node app (you guessed right, I am trying to SSR react stuff ;) )
src/Html.js -(webpack)-> build/ssr-bundle.js
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import CustomComponent from './custom-component.js';
module.exports = {
render : function () {
return ReactDOMServer.renderToString(<CustomComponent />);
} };
And here is my Webpack config
webpack.config.js
var path = require('path');
module.exports = {
entry: {
ssr: './src/Html.js',
//frontend: './src/frontend-Html.js'
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'ssr-bundle.js',
library: 'ssrbundle'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env','react'],
plugins: ["transform-es2015-destructuring", "transform-object-rest-spread"]
}
},
{
test:/\.css$/,
use:['style-loader','css-loader']
}
]
},
stats: {
colors: true
},
devtool: 'source-map'
};
Whatever I do, I cannot figure out how to properly use that exported variable "ssrbundle" and subsequently the render function. If I had my node app included in the bundle, everything would be all right, but this is not what I want to do.
As apokryfos suggested, I played around with the libraryTarget Webpack setting. You can find more info on using Webpack to author a library (what I was really trying to achieve) here:
https://webpack.js.org/guides/author-libraries/
and here are code examples:
https://github.com/kalcifer/webpack-library-example/blob/master/webpack.config.babel.js.
What did the trick for me, was to set the libraryTarget to "umd" , which is different than the "var" setting which is set by default and is suitable i.e. for including the script in an HTML file
I'm trying to integrate redux into an existing react application. All of my react code is within jsx files. Now i'm introducing redux and a store.js. during the compilation webpack errors on an exepected token error on store.js
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'project/static/public/js');
var APP_DIR = path.resolve(__dirname, 'project/static/public/js/components');
module.exports = {
entry: APP_DIR + '/App.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules', 'react')
}
},
module : {
loaders : [
{
test : /\.jsx/,
include : APP_DIR,
loader : 'babel',
presets : ['es2015']
},
{
test : /\.js/,
include : BUILD_DIR,
exclude : /bundle.js||bundle.js.map||node_modules/,
loader : 'babel',
presets : ['es2015']
}
]
},
watchOptions: {
poll: true
}
};
.babelrc
{
"presets": [
"es2015",
"react"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
}
},
"plugins": [
["transform-es2015-arrow-functions", { "spec": true }],
["transform-class-properties"]
]
}
store.js
import { applyMiddleware, createStore} from 'redux';
import combineReducers from './reducers/index.js'
export default createStore(combineReducers)
error message
ERROR in ./project/static/public/js/store.js
Module parse failed: /home/username/git/project/project/static/public/js/store.js Line 1:
Unexpected token
You may need an appropriate loader to handle this file type.
| import { applyMiddleware, createStore} from 'redux';
| import combineReducers from './reducers/index.js'
|
# ./project/static/public/js/components/App.jsx 15:13-32
These files have gone through multiple iterations in trying to resolve and better understand redux. I think the problem is with my webpack configuration.
Which version of Babel are you using? I guess that you need to use the babel-loader in the webpack rule. This configuration works fines with Babel 7 and Webpack 4.
WEBPACK RULE:
{
test: /\.js$/,
include : BUILD_DIR,
exclude : /bundle.js||bundle.js.map||node_modules/,
use: {
loader: 'babel-loader',
},
},
And .babelrc file example:
{
"presets": [[
"#babel/preset-env", {
"useBuiltIns": "entry"
}],
"#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-export-default-from",
"react-hot-loader/babel"
]
}
Please, keep in mind you need to install babel-loader at least version 8.0.0, babel core 7.0.0 and webpack 4.23.
But, I'm pretty sure that the problem is that you need to use the babel-loader plugin in webpack. Visit https://github.com/babel/babel-loader
Best!
I am working on a react application. Where I am using webpack and babel loader.
In my react application I am using import statement many times which is working fine.
Now I have My another stand alone application which is working fine.
Now I am installing my standalone application in react application using npm. So I do
let standAloneApplication = require("my_stand_alone_application")
But I get import error inside the standAloneApplication. Where I have a line
import controller from "./controller" // Main.js:1Uncaught SyntaxError: Unexpected token import
where as import statement in React application works fine. also the stand alone application work fine at alone. but together It's giving SyntaxError
my webpack file
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'html');
var APP_DIR = path.resolve(__dirname, 'html');
var config = {
entry: APP_DIR + '/app.js',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
devtool: "source-map",
node: {
fs: "empty"
} ,
module : {
loaders : [
{
test : /\.js?/,
include : APP_DIR,
exclude: /node_modules/,
loaders: ['babel?presets[]=react,presets[]=es2015,plugins[]=transform-decorators-legacy,plugins[]=transform-class-properties,plugins[]=transform-export-extensions'],
},
{ test: /\.json$/, loader: "json" }
]
}
}
module.exports = config;
main.js Code from stand alone application
import {Controller} from "./Controller/index.js"
export class Main () {
}
Notice the exclude: /node_modules/ in your loader setup.
Since you installed your app/module using npm, it's located in that directory, and because of the exclusion it will not be transpiled by Babel.
Perhaps, but I'm not sure, you can add it explicitly to the include line:
include : [
APP_DIR,
path.resolve(__dirname, 'node_modules/my_stand_alone_application')
]