This question already has answers here:
babel-loader jsx SyntaxError: Unexpected token [duplicate]
(8 answers)
Closed 6 years ago.
I am trying to build my app using wepback and getting getting stuck at this unexpected token error. All the dependencies for my project are fine and upto date I am using the same project somewhere else and it is building fine but when I try to build my current code which is same it gives the error, below are config.js and error descriptions
Here is my app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router';
import Routes from '../routes/routes';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { browserHistory } from 'react-router';
require('../Config');
injectTapEventPlugin();
window.EventEmitter = {
_events: {},
dispatch: function (event, data, returnFirstResult) {
if (!this._events[event]) return;
for (var i = 0; i < this._events[event].length; i++)
{
if(this._events[event][i])
{
var r = this._events[event][i](data);
if(returnFirstResult)
return r;
}
}
},
subscribe: function (event, callback, onlyOne) {
if (!this._events[event] || onlyOne) this._events[event] = []; // new event
this._events[event].push(callback);
}
};
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
Here is my config.js
var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, '../project/public/js/');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var TransferWebpackPlugin = require('transfer-webpack-plugin');
var config = {
entry: {
app: path.join(__dirname, '/app/entry_points/app.jsx'),
vendor: ['react', 'radium'],
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
devtool: 'source-map',
output: {
path: buildPath,
publicPath: '/js/',
filename: 'mobile.[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "mobile.vendor.js"),
new webpack.DefinePlugin({}),
new webpack.NoErrorsPlugin(),
],
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
include: [path.resolve(__dirname, "src/app")],
exclude: [nodeModulesPath]
},
],
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath]
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
]
},
eslint: {
configFile: '.eslintrc'
},
};
module.exports = config;
This is the error I get when I try to build:
ERROR in ./app/entry_points/app.jsx
Module build failed: SyntaxError: /home/zeus/Glide/project/project-mobile/app/entry_points/app.jsx: Unexpected token (46:16)
44 | // Render the main app react component into the app div.
45 | // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
> 46 | ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
| ^
I am using react v0.14.8, react-dom v0.14.8, babel-loader ^6.2.1
i believe you need to specify the presets with babel and install the npm module babel-preset-react
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath],
query: {
presets: ['react']
}
},
...
]
you'd also want to add es2015 to that presets array if you're using it.
Related
I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,
I'm trying to follow this video but I'm running into this error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (5:4)
I followed everything in the video but I don't see where I'm going wrong.
Webpack.config.js:
const path = require('path')
module.exports = {
entry: {
app: './src/index.js'
},
watch: true,
devtool: 'source-map',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname,'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: [
'.js'
]
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div>
<h1>Test</h1>
</div>,
document.getElementById("root")
)
JSX syntax has to be compiled with Babel before you can load it in the browser.
To do this you can add a .babelrc file to the root of the project:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Babel Preset React
I am trying to use React, Typescript, Webpack 3 and Bootstrap 4 to create a basic working project. When I import bootstrap.css in main .tsx file I am getting error like Unexpected Symbol - # - in /node_modules/bootstrap/dist/css/bootstrap.css.
Below is my webpack.config.js file :
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './src/app.tsx'
},
output: {
path: path.join(__dirname,'dist'),
filename: '[name].bundle.js'
},
watch:true,
resolve: {
extensions: ['.ts','.tsx','.js']
},
devServer: {
contentBase: path.join(__dirname,'dist'),
port: 3333
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: ['awesome-typescript-loader']
},
{
test: /.html$/,
use: ['raw-loader']
},
{
test: /\.json$/,
use: ['json-loader']
},
{
test: /\.(s)css$/,
exclude: /node_modules/,
use: ['css-loader','style-loader','sass-loader',{
loader: 'postcss-loader', // Run post css actions
options: {
plugins: function () { // post css plugins, can be exported to postcss.config.js
return [
require('precss'),
require('autoprefixer')
];
}
}
},]
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
showErrors: true,
title: 'React TS Webpack App'
}),
]
}
And the below App.tsx file:
import 'bootstrap/dist/css/bootstrap.css';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Greet from './components/Greet';
const techStack = ['React','TypeScript','Webpack','Bootstrap'];
ReactDOM.render(<Greet techs={techStack}/>, document.getElementById('app'));
But I am getting the below error:
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.css
Module parse failed: Unexpected character '#' (7:0)
You may need an appropriate loader to handle this file type.
| * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
| */
| #media print {
| *,
| *::before,
# ./src/app.tsx 1:0-42
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/app.tsx
Could anybody help me how to clear this error and make bootsrap and webpack work?
"Use" style-loader before css-loader...
use: ['style-loader','css-loader','sass-loader',{ ... }..]
I am trying to bootstrap an AngularJS app built with Webpack. But I get the following error and the module isn't set up.
TypeError: _angular.angular is undefined
I dig into the generated code chunk and find that the _angular.angular is from
var _angular = __webpack_require__(1);
var _angularUiBootstrap = __webpack_require__(3);
_angular.angular.module('app', [_angularUiBootstrap.bootstrap]).constant('_', window._).run(function ($rootScope) {
$rootScope._ = window._;
It looks like that _angular.angular.module should be _angular.module. I probably use a wrong way to bootstrap angular, or use an incorrect Webpack configuration. Here is my code:
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var srcDir = 'static_src';
var outputDir = 'static';
module.exports = {
devtool: 'source-map',
debug: true,
entry: {
app: path.resolve(srcDir, 'app.js')
},
output: {
path: outputDir,
filename: '[name].bundle.js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: ['', '.js', '.less', '.css'],
alias: {
npm: __dirname + '/node_modules'
}
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015'],
plugins: ['syntax-decorators', 'ng-annotate']
},
exclude: /node_module/
},
{ test: /\.less$/, loader: 'to-string!css!less' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.(png|gif|jpg)$/, loader: 'file?name=images/[name].[ext]' }
]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new ExtractTextPlugin('[name].css')
]
};
app.js
import { angular } from 'angular';
import { bootstrap } from 'angular-ui-bootstrap';
angular.module('app', [bootstrap]);
I am using angular 1.5.0 and webpack 1.12.14.
Thanks in advance.
your error is in the require statement. you are using
import { angular } from 'angular';
this implies that there is an angular variable inside of the exported angular module.
what you want to use is
import angular from 'angular';
try that.
Trying to support IE 9 for React. Upgraded to use babel 6.3.26 and babel-preset-es2015 and babel-preset-react for Webpack. However, when the file is loaded in IE 9, a syntax error occurs.
webpack.config.js
/* eslint-env node */
var path = require('path');
var packageJson = require('./package.json');
var _ = require('lodash');
var webpack = require('webpack');
var context = process.env.NODE_ENV || 'development';
var configFunctions = {
development: getDevConfig,
production: getProdConfig,
test: getTestConfig
};
var config = configFunctions[context]();
console.log('Building version %s in %s mode', packageJson.version, context);
module.exports = config;
function getLoaders() {
if (context.indexOf('test') === -1) {
return [
{
test: /\.js?$/,
exclude: /(test|node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
plugins: ['transform-runtime']
}
}
]
} else {
return [
{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
plugins: ['transform-runtime']
}
}
]
}
}
function getBaseConfig() {
return {
context: __dirname + "/src",
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
stats: {
colors: true,
reasons: true
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: _.union(
getLoaders(),
[
{
test: /\.scss$/,
loader: 'style!css!sass'
},
{
test: /\.eot$|\.svg$|\.woff$|\.ttf$/,
loader: 'url-loader?limit=30000&name=fonts/[name]-[hash:6].[ext]'
},
{
test: /\.(png|.jpe?g|gif)$/,
loader: 'url-loader?limit=5000&name=img/[name]-[hash:6].[ext]'
},
{
test: /\.mp4$/,
loader: 'url-loader?limit=5000&name=videos/[name]-[hash:6].[ext]'
}
]
)
}
};
}
function getDevConfig() {
return _.merge({}, getBaseConfig(), {
devtool: 'cheap-module-eval-source-map',
entry: [
'babel-polyfill',
'webpack-hot-middleware/client',
'./App'
],
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
eslint: {
emitError: false,
failOnError: false,
failOnWarning: false,
quiet: true
}
});
}
function getProdConfig() {
return _.merge({}, getBaseConfig(), {
devtool: 'source-map',
entry: [
'babel-polyfill',
'./App'
],
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false
}
})
],
eslint: {
emitError: true,
failOnError: true
}
})
}
function getTestConfig() {
return _.merge({}, getBaseConfig(), {})
}
Checking bundle.js for the offending lines reveals the usage of const which is not ES5. Am I missing something here? Do I need to transpile ES6 code into ES5 for production usage?
IE9 is not compatible with ES6, so, yes, you must transform your ES6 code to ES5. I believe the problem is you aren't telling babel to use the react and es2015 presets. I'm sure you installed them on your machine, but the babel loader only does what you tell it.
Inside your getLoaders() function, add the presets to your babel loader configuration query:
query: {
plugins: ['transform-runtime'],
presets: ['react', 'es2015']
}
Hopefully, that works for you.
babel/babel-loader reference
I am using create-react-app (v16.4.2). I tried using the followings to get the default hello world working in IE9:
1:
import 'core-js/es6/map';
import 'core-js/es6/set';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
2:
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
But neither of them worked for me. I ended up adding the following line into my index.html file in the public folder and it fixed my issue:
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
More information is available at:https://polyfill.io/v2/docs/