I'm having some sort of issue getting React to play nice with web pack and render in this project. I'm getting a syntax unexpected token error.
console error
here is my main.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MyComponentClass extends React.Component {
render() {
return 'Test Component';
}
}
ReactDOM.render( <MyComponentClass />, document.getElementById('root'));
here is my Webpack.config file:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const config = {
entry: {
app: './client/scripts/main.js',
},
output: {
filename: 'app.js',
path: path.join(__dirname, 'public')
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
include: __dirname + '/client/scripts',
loader: 'babel-loader',
},
{
test: /\.css$/,
loader: ['css-hot-loader'].concat(ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
localIdentName: '[name]__[local]'
}
},
{
loader: 'postcss-loader',
},
],
})),
},
{
test: /\.html/,
loader: 'html-loader',
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: 'file-loader',
options: {
hash: 'sha512',
digest: 'hex',
name: 'images/[name].[ext]',
},
},
],
},
plugins: [
new ExtractTextPlugin({
filename: 'app.css',
ignoreOrder: true,
}),
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['.css', '.js'],
modules: [
path.join(__dirname, 'src'),
'node_modules',
],
},
devServer: {
contentBase: path.join(__dirname, "public"),
hot: true,
port: 8005,
}
};
module.exports = config;
And my package.json
{
"name": "jumpcloud-ui-assignment",
"version": "1.0.0",
"description": "A project that can be used to asses front end developers",
"repository": {
"type": "git",
"url": "git://github.com/TheJumpCloud/jumpcloud-ui-assignment.git"
},
"private": true,
"author": "JumpCloud",
"bugs": {
"url": "https://github.com/TheJumpCloud/jumpcloud-ui-assignment/issues"
},
"scripts": {
"start:client": "webpack-dev-server --progress --inline",
"start:server": "node server/server.js"
},
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"body-parser": "^1.15.2",
"express": "^4.14.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"underscore": "^1.8.3"
},
"devDependencies": {
"autoprefixer": "^7.1.6",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"css-hot-loader": "^1.3.3",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"postcss-loader": "^2.0.8",
"script-loader": "^0.7.2",
"style-loader": "^0.19.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}
Im sure it's a webpack configuration issue, after scowering the other similar issues here im coming up blank.
Add a '.babelrc' file to your project containing
{
"presets": [ "es2015", "react" ]
}
And it should be ok
Related
I have a basic React app (2 small pages and a redux store), which is supposed to be very light. But when building the final bundle, webpack tells me that the bundle is 1.12 MiB, while the recommended limit is 244 KiB. Yet, I have made optimisations, with Terser plugin & code splitting.
Here is my webpack.config.js:
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const Dotenv = require("dotenv-webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = () => {
const env = require("dotenv").config({ path: __dirname + "/.env" });
return {
mode: "development",
entry: "./src/Index.js",
output: {
path: path.join(__dirname, "./dist"),
filename: "[name].[hash].bundle.js",
publicPath: "/",
},
resolve: {
extensions: [".js", "jsx", ".json"],
alias: {
components: path.resolve(__dirname, "src/components/"),
pages: path.resolve(__dirname, "src/pages/"),
store: path.resolve(__dirname, "src/store/"),
src: path.resolve(__dirname, "src/"),
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
{ test: /\.html$/, use: [{ loader: "html-loader" }] },
],
},
devServer: {
historyApiFallback: true,
port: 3000,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
new Dotenv(),
],
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
splitChunks: { chunks: "all" },
},
};
};
And here is my package.json:
{
"name": "app",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production",
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router-dom": "^5.2.0",
"redux": "^4.0.5"
},
"devDependencies": {
"#babel/core": "^7.10.3",
"#babel/plugin-transform-runtime": "^7.10.3",
"#babel/preset-env": "^7.10.3",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"dotenv-webpack": "^1.8.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.3.0",
"terser-webpack-plugin": "^3.0.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
How to fix this?
I'm new to React, webpack, Babel.... all of it. Trying to setup a vanilla project where I want to utilize Salesforce Lightning Design System for React. npm run start shows the following error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] /Users/brandor/test/react_tut/src/index.js: Cannot find module 'babel-preset-env'
Require stack:
- /Users/brandor/test/react_tut/node_modules/#salesforce/babel-preset-design-system-react/index.js
I'm not sure why it's stating that 'babel-preset-env' is required. Shouldn't that have been installed when I installed the slds modules with the following?
$ npm install #salesforce-ux/design-system #salesforce/design-system-react
If I do install the module (along with one other it complains about) then I get something that seems to be related to this issue, but I'm using what looks like the correct presets in my babel.config.js file.
The other error is:
TypeError: /Users/brandor/test/react_tut/src/components/App.js: Cannot read property 'bindings' of null which
Not sure if this is an issue with webpack config, babel, or incorrect version of something.
package.json
{
"name": "react_tut",
"version": "1.0.0",
"description": "Boilerplate stuff",
"main": "index.js",
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open --hot"
},
"license": "MIT",
"dependencies": {
"#salesforce-ux/design-system": "^2.11.6",
"#salesforce/design-system-react": "^0.10.18",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0",
"core-js": "^3.6.4",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-flow": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"url-loader": "^4.0.0",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
resolve: {
modules: ['src', 'node_modules'],
extensions: ['.js', '.jsx']
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, 'src/js'),
path.join(__dirname, 'node_modules/#salesforce/design-system-react'),
],
exclude: [
path.join(
__dirname,
'node_modules/#salesforce/design-system-react/node_modules',
),
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(svg|gif|jpe?g|png)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|woff|woff2|ttf)$/,
loader: 'url-loader?limit=30&name=assets/fonts/webfonts/[name].[ext]'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
}),
],
};
babel.config.js
'use strict';
const presets = ['#babel/preset-react', '#babel/preset-flow', '#salesforce/babel-preset-design-system-react'];
module.exports = {
presets: [
...presets,
[
'#babel/preset-env',
{
modules: false,
corejs: '3',
useBuiltIns: 'usage',
},
],
],
env: {
test: {
presets: [
...presets,
[
'#babel/preset-env',
{
targets: { node: 'current' },
corejs: '3',
useBuiltIns: 'usage',
},
],
],
},
},
};
I'm having a different problem from the one here. babel-plugin-react-css-modules is not matching styles with styleName
I'm trying to search for the app class in my App.jsx file to confirm I've setup babel-plugin-react-css-modules with Enzyme. Unfortunately, I clearly haven't done so successfully, even though i seem to be following the supposed solution here: https://github.com/gajus/babel-plugin-react-css-modules/issues/168 (although I'm using Jest)
I'd really appreciate any help.
App.jsx
import React from 'react';
import { hot } from 'react-hot-loader/root';
import './App.css';
const App = () => (
<div styleName="App">
<h1>Hello World!</h1>
</div>
);
export default hot(App);
App.test.js
import {mount} from 'enzyme';
import React from 'react';
import App from './App';
it('has an App component which returns a div with the class named App', () => {
const wrapper = mount(<App />);
expect(wrapper.find('.app')).toHaveLength(1);
})
test failure message
Expected length: 1
Received length: 0
Received object: {}
I've confirmed that the issue is due to transpilation because the test passes when I search for the class App__App___1o-Fp which is what it appears as on localhost.
.babelrc
{
"env": {
"test": {
"presets": ["#babel/env", "#babel/preset-react"],
"plugins": [
[
"react-css-modules",
{
"generateScopedName": "[local]"
}]
]
}
},
"presets": ["#babel/env", "#babel/preset-react"],
"plugins": ["react-hot-loader/babel", [
"react-css-modules",
{
"generateScopedName": "[name]__[local]___[hash:base64:5]"
}
]
]
}
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.jsx",
mode: "development",
module: {
rules: [
{
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "eslint-loader",
options: {
fix: true
}
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: ["babel-loader", "react-hot-loader/webpack"],
},
{
test: /\.css$/,
use: ["style-loader", {loader: "css-loader", options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
},
resolve: {
alias: {
'react-dom': '#hot-loader/react-dom'
},
extensions: ["*", ".js", ".jsx"]
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
package.json
{
"name": "shopping-page",
"version": "1.0.0",
"description": "Hi!",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+ssh://git#gitlab.com/mgoldwater-nisum-com/shopping-page.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://gitlab.com/mgoldwater-nisum-com/shopping-page/issues"
},
"homepage": "https://gitlab.com/mgoldwater-nisum-com/shopping-page#README",
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.3.1",
"#babel/preset-react": "^7.0.0",
"#hot-loader/react-dom": "^16.8.1",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.5",
"babel-plugin-react-css-modules": "^5.0.0",
"css-loader": "^2.1.0",
"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.9.1",
"eslint-loader": "^2.1.2",
"file-loader": "^3.0.1",
"identity-obj-proxy": "^3.0.0",
"jest": "^24.1.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-hot-loader": "^4.6.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.1.14"
},
"devDependencies": {
"eslint": "^5.13.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.12.4"
},
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"moduleNameMapper": {
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
}
}
}
I have the following configuration for a react based application that is failing JSX parsing during webpack build:
ERROR in ./src/App.jsx
Module parse failed: /Users/sangupta/git/plx/ui2/src/App.jsx Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
|
| render() {
| return <div class='hello'>Hello World</div>;
| }
|
# multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server src/App.jsx
Any suggestions on what might be wrong?
The following is the package.json file:
{
"name": "Test-Project",
"version": "0.1.0",
"private": true,
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "0.28.4",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.30.1",
"less": "2.7.1",
"less-loader": "2.2.3",
"postcss-loader": "2.0.5",
"style-loader": "0.13.2",
"webpack": "3.4.1",
"webpack-dev-server": "2.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"scripts": {
"build": "webpack",
"build-production": "NODE_ENV=production npm run build",
"watch": "webpack-dev-server --hot --progress"
}
}
The following is webpack.config.json file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
context: __dirname,
entry: {
app: 'src/App.jsx',
vendor: [ "react", "react-dom" ]
},
devServer: {
contentBase: path.join(__dirname, 'assets'),
compress: true,
port: 9000,
hot: true,
https: false,
noInfo: false,
historyApiFallback: true
},
resolve: {
extensions: [ '.js', '.jsx' ],
alias: {
src: './src'
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
module: {
rules: []
},
// Tell webpack to use html plugin
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new webpack.ProvidePlugin({
'React': 'react',
}),
new UglifyJsPlugin({ sourceMap: !isProduction }),
new HtmlWebpackPlugin({ title: 'MultiPLX', template: 'src/index.ejs', inject : 'body' })
]
};
You should be using the react babel preset:
npm install --save-dev babel-preset-react
webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "react", "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},
I'm learning react and I want to test one of my components but I'm stuck with this error:
{import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
Here's some things I have tried from reading post on stackoverflow and github
added test presets and these plugins "transform-es2015-modules-commonjs", dynamic-import-node" to my babel config
{
"presets": ["es2015", "react"],
"env": {
"test": {
"presets":[
["es2015", { "modules": false }],
"stage-0",
"react"],
"plugins": [
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
}
}
In my package.json the Jest property has these settings:
"jest": {
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"jsx",
"js"
],
"transform": {},
"moduleDirectories": [
"node_modules"
],
"transformIgnorePatterns": [
"node_modules/(?!react)/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
},
My actual component is built with ES6 and typescript if that helps you help me :)
From what I have read, it seems jest chokes on import because node doesn't understand ES6 import. None of the solutions I have tried online have seemed to work.
Also here are my dev Dependencies:
"devDependencies": {
"awesome-typescript-loader": "^3.2.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.4",
"enzyme": "^2.9.1",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.2.0",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-harddisk-plugin": "^0.1.0",
"html-webpack-plugin": "^2.30.1",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-test-renderer": "^15.6.1",
"regenerator-runtime": "^0.10.5",
"sass-loader": "^6.0.6",
"source-map-loader": "^0.2.1",
"style-loader": "^0.18.2",
"ts-jest": "^20.0.10",
"typescript": "^2.4.2",
"webpack": "^3.5.1",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^2.7.0"
},
Webpack config
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const HOST = "127.0.0.1";
const PORT = "9000";
const devServerUrl = "http://localhost:" + PORT + "/";
const config = {
devtool: 'source-map',
context: __dirname, // `__dirname` is root of project and `src` is source
entry:
[
'./src/index.js',
'./src/ui/styles.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js",
publicPath: ''
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{ test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{
test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
devServer: {
contentBase: "dist/",
noInfo: true,
inline: true,
compress: true,
port: PORT,
host: HOST,
hot: true
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html', // Output file name.
template: './public/index.html', // Use our HTML file as a template for the new one.
inject: 'body',
alwaysWriteToDisk: true,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
}),
new ExtractTextPlugin({ // define where to save the file
filename: 'styles.bundle.css'}),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackHarddiskPlugin({
outputPath: path.resolve(__dirname, 'dist')
})
],
};
module.exports = config;
Thanks
Jest doesn't work with Typescript.
I have removed Jest from my project and installed Mocha, Karma, Chai & Enzyme.
Effortless to set up compared to Jest which masquerades as a:
Zero configuration testing platform
This article was a huge help: Getting Started on Testing with Typescript, ReactJS, and Webpack.
Hopefully this will save others from wasting their time getting Jest to work with Typescript.
It's because you have configured babel to not transpile ES6 modules
"presets":[
["es2015", { "modules": false }],
Try again with that modules to true (or omitted, since it defaults to true) and it should work.
you need to install babel to compile your es6 and react code
do it using
C:\Users\username\Desktop\reactApp>npm install babel-core
C:\Users\username\Desktop\reactApp>npm install babel-loader
C:\Users\username\Desktop\reactApp>npm install babel-preset-react
C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015
Try to keep our webpack as
var config = {
entry: './todoApp.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 9191
},
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;