Babel not transpiling JSX from files above current directory - reactjs

I have a monorepo set up with a file structure like:
/root
/-ProjectA
/-ProjectB
/-common
In /ProjectA, I have a React app which imports a file from /common. When I try to start it in the Webpack Dev Server, I get an error from Babel-Loader saying that there is a compilation error in the imported common file where the JSX starts.
If I move the common file into ProjectA and import from there, everything works fine so there is no problem in that specific file (plus it's a very simple contrived example at this point).
/common/index.js (this is the only files in this directory)
import React from 'react';
export default () => <span>Hello, World!</span>;
/ProjectA/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from '../common';
const App = () => <div><Hello /></div>;
ReactDOM.render(<App />, document.querySelector('#root'));
/ProjectA/.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
/ProjectA/webpack.config.js
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: [
path.resolve('.'),
path.resolve('../common'),
],
use: {
loader: 'babel-loader'
}
}
/ProjectA/package.json
{
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"#babel/core": "^7.5.4",
"#babel/preset-env": "^7.5.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
}
}
Why is babel unable to transpile files from outside the current directory? Is there a way around this or a problem in my configs maybe?

Add this line to webpack.config.js
devServer: { contentBase: path.join(__dirname, "public") }
add this script to package.json
"scripts":{
"dev-server": "webpack-dev-server",
}
config.webpack.js(without styling loaders)
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
now this command should run your app.
npm run dev-server

Related

Bundling AWS Amplify UI with WebPack - Uncaught SyntaxError: Invalid or unexpected token

I am trying to use AWS Amplify UI in a React project. However, I receive the following errors after bundling the project with WebPack: Uncaught SyntaxError: Invalid or unexpected token (in Chrome) & SyntaxError: Invalid character '\u00b0' (in Safari). The error does not appear in Firefox.
This occurs when I load the bundled HTML file, after bundling with the webpack command. However, when using webpack serve, I have observed that the page renders as expected, in all the above browsers, with no errors.
package.json
{
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.17.12",
"babel-jest": "^27.5.1",
"babel-loader": "^8.2.5",
"copy-webpack-plugin": "^10.2.4",
"css-loader": "^6.7.1",
"eslint": "^8.14.0",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.5.1",
"node-polyfill-webpack-plugin": "^1.1.4",
"pa11y": "^6.2.3",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.8.1"
},
"dependencies": {
"#aws-amplify/ui-react": "^3.0.1",
"#fontsource/poppins": "^4.5.8",
"aws-amplify": "^4.3.26",
"jquery": "^3.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = (env, argv) => {
let filename = "[name]-bundle.js";
if (argv.mode == "production") {
filename = "[name]-bundle-[contenthash].js";
}
let config = {
entry: {
app: './src/app.js'
},
output: {
filename,
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
importLoaders: 1,
sourceMap: true
}
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: "index.html",
chunks: ["app"]
}),
new NodePolyfillPlugin()
],
devtool: 'inline-source-map',
devServer: {
static: './dist',
allowedHosts: "all"
}
};
return config;
};
app.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Button } from '#aws-amplify/ui-react';
import '#aws-amplify/ui-react/styles.css';
import "#fontsource/poppins/index.css";
function App() {
return (
<div>
<p>Testing</p>
<Button variation="primary">Hello world</Button>
</div>
);
}
const domContainer = document.getElementById("container");
const root = ReactDOM.createRoot(domContainer);
root.render(<App />);
This is a character encoding issue.
It worked with the WebPack DevServer because charset=utf-8 is automatically appended to the Content-Type header of the response.
Setting the character encoding in the head of the HTML file, as below, resolved this issue.
<meta charset="utf-8" />

Cant Import CSS files into React Project

when i tried to import css file it showed error that loaders are missing. so i have installed css-loader and style-loader packages. if i add those packages to webpack.config.js i get following error. i dont know how to resolve it.
ERROR in ./node_modules/css-loader!./src/index.js
Module build failed: Unknown word (1:1)
> 1 | import React from 'react';
| ^
2 | import ReactDOM from 'react-dom';
3 | import {App} from './components/App';
4 |
# ./src/index.js 3:14-73
# multi (webpack)-dev-server/client?http://localhost:8080
./src/index.js
Webpack.config.js
module.exports = {
entry: [
'./src/index.js'
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader","style-loader","css-loader"],
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
i have installed following dependecies
package.json
{
"name": "Reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode
development"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"style-loader": "^0.20.3",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2"
}
}
Modifie your webpack.config.js to this and import your css file on your App component like this import './file.css'; (assuming that the css file is in the same directory as your App component)
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
You need to add a separate rule for css to your webpack.config in order to load css into your project.
...
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
...
You're using style-loader and css-loader to transform your .jsx files which is going to throw an error.

Compiling react with webpack syntax error

I'm a little bit new to webpack with babel loader and eslint
and I'm trying to compile a very basic application
and I get this weird syntax error that I can't figure out
This is my index.js, where I get the compiling error
const store = configureStore()
render(
<Router>
<Root store={ store } />
</Router>,
document.getElementById('console_root')
)
and this is the error I get:
ERROR in ./src/index.js
Module build failed: SyntaxError: Unexpected token (19:2)
17 |
18 | render(
> 19 | <Router>
| ^
20 | <Root store={ store } />
21 | </Router>,
22 | document.getElementById('console_root')
npm ERR! code ELIFECYCLE
npm ERR! errno 2
and this is my webpack.config.js file
var webpack = require('webpack')
var path = require('path')
module.exports = {
entry: {
main: path.resolve(__dirname, 'src', 'index.js')
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: path.resolve(__dirname, '..'),
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
})
]
}
and these are my dependencies:
"dependencies": {
"material-ui": "^1.0.0-beta.26",
"material-ui-icons": "^1.0.0-beta.17",
"prop-types": "^15.6.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"redux": "^3.7.2"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.1.2",
"babel-loader": "^7.1.2",
"css-loader": "^0.28.7",
"eslint": "^4.14.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-react": "^7.5.1",
"react-scripts": "^1.0.17",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.1",
"webpack": "^3.10.0"
}
any ideas what am I doing wrong?
Seems like you missed to add react preset to your webpack.config.js file or to .babelrc.
First you should install it: npm i babel-preset-react --save-dev
Then add react preset to your webpack config like the following
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['react']
}
}
}
]
}
Or create a new file called .babelrc and add it there
// .babelrc
{
"presets": ["react"]
}
It should work for you.
I guess you need to create a .babelrc file with content in it
{
"presets": [
"es2015",
"react"
],
}
This will tell babel to transpile es6 to es5 and also tell there is a react project and it will handle accordingly.For these there are two packages you need which will do the job
npm install babel-preset-es2015 --save
npm install babel-preset-react --save
Check this blog for more info

Unable to build ES6 version of my React App with webpack and babel-preset-env [duplicate]

This question already has answers here:
Webpack + Babel error
(2 answers)
Closed 5 years ago.
I decided to rewrite my existing React App from ES5 to ES6. Below is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ToDoList from './to-do-list.jsx';
//Put the components into HTML
ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
However when I try to build with webpack and launch the app I get the error that:
ERROR in ./src/app/index.js
Module parse failed: /home/sam/devzone/github/simple-react-todo-app/src/app/index.js Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
|
| //Put the components into HTML
| ReactDOM.render(<ToDoList/>, document.getElementById('todo-wrapper'));
I have selected babel-preset-env instead of babel-preset-es2015, but I highly doubt that this is the cause. Below are snapshots of my package.json and my webpack.config.js respectively.
package.json
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --content-base src/ --inline --hot --port 1234"
},
...
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.7",
"eslint": "^4.7.2",
"eslint-plugin-react": "^7.4.0",
"style-loader": "^0.18.2",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
],
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};
As it might be evident that I did a bit trial and error myself, but I seem to be totally lost now.
The app folder structure and other relevant files can be seen inside my repo here.
Any pointers would be appreciated.
Your webpack's config is wrong (it's old config from Webpack 1)
You should change it to:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/app/index.js',
output: {
path: path.resolve(__dirname, 'dist') + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
options: {
"presets": [
["env", {
"loose": true,
"modules": false,
"useBuiltIns": true,
"debug": true,
"include": ["transform-es2015-classes"]
}],
"react"
],
"plugins": [
"babel-plugin-transform-es2015-parameters",
"babel-plugin-transform-es2015-destructuring"
]
}
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
};
Just change
test: /\.jsx?$/,
To
test: /.(js|jsx)?$/,

Webpack error interpreting React modules/files

Currently I have two files in my webpack script build, script.js and contact-menu.js. If I create react components on the main script.js file, it translates ok. If create React components in contact-menu.js and try export import it gives the following error:
> ERROR in ./babel/contact-menu.js Module parse failed:
> /Applications/MAMP/htdocs/mcdonalds excavation/themes/mcdonalds/babel/contact-menu.js
> Unexpected token (7:3) You may need an appropriate loader to handle
> this file type. | render(){ | return( | <div
> id="contact-menu-container"> | <div id="contact-menu-btn"> |
> Close # ./babel/script.js 11:19-47
I have tried renaming the files from js to jsx, aswell as changing the entry point on my webpack config
webpack config
var path = require('path');
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: './babel/script.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'script.js'
},
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
include: [path.resolve(__dirname, 'babel/script.js')],
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3'],
plugins: ['transform-react-jsx']
}
}, {
test: /\.scss$/,
include: [path.resolve(__dirname, 'sass')],
loaders: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader"
}]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
sourcemap: false
}),
],
};
package.json
{
"name": "react-kit",
"version": "3.0.0",
"description": "React Build Kit With Webpack.",
"main": "webpack.config.js",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"axios": "^0.15.3",
"babel-cli": "^6.18.0",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-plugin-transform-react-jsx": "^6.8.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.5.0",
"css-loader": "^0.26.1",
"fetch-jsonp": "^1.0.6",
"history": "^1.17.0",
"node-sass": "^4.5.0",
"react-router": "^3.0.1",
"sass-loader": "^5.0.1",
"style-loader": "^0.13.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.14.1"
},
"author": "",
"license": "MIT"
}
script.jsx
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<ContactMenu />,
document.getElementById('contact-menu')
)
contact-menu.jsx
import React from 'react'
import ReactDOM from 'react-dom'
export default class ContactMenu extends React.Component{
render(){
return(
<div id="contact-menu-container">
<div id="contact-menu-btn">
Close
</div>
<div id="contact-menu">
</div>
</div>
)
}
}
I believe this line in your webpack configuration is the problem:
include: [path.resolve(__dirname, 'babel/script.js')],
The webpack documentation is fairly sparse, but it appears that if include is specified only the paths in it will be transformed by the loader. If you omit that option, all paths that pass test and aren't listed in exclude should be transformed by the loader, including contact-menu.js.

Resources