SyntaxError in ./index.html - javascript

I'm trying to convert my create-react-app to a Webpack compatible app.
I can't understand clearly what I'm done and I often get into an error:
ERROR in ./index.html
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /mnt/c/Users/.../index.html: Unexpected token (1:0)
> 1 | <!doctype html>
| ^
2 | <html>
3 | <head>
4 | <title>Getting Started</title>
at Object._raise [...]
This happens after launching npm start
This is my configuration:
Structure
index.html
webpack.config.js
babelrc
src/index.js
package.json
./index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash#4.16.6"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
./src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
./webpack.config.js
const webpack = require('webpack');
const path = require('path');
const config = {
entry: [
'react-hot-loader/patch',
'./index.html'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$|jsx$|html/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/react']
}
}
]
},
resolve: {
extensions: [
'.js',
'.jsx',
'.html'
],
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
devServer: {
contentBase: './dist'
}
};
module.exports = config;
Finally, my ./.babelrc
{
"plugins": ["#babel/transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
I've this dependencies in my package.json:
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"#hot-loader/react-dom": "^17.0.0-rc.2",
"babel-loader": "^8.1.0",
"babel-plugin-import": "^1.13.0",
"css-loader": "^4.3.0",
"react-hot-loader": "^4.5.3",
"style-loader": "^1.2.1",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}

You're using a javascript loader for your html, this is not going to work.
You should use the html-loader instead

Related

How do you use webpack-merge and react?

I have been trying to make a webpack config for a react based app, it was working before I started using webpack-merge and had the single webpack.config.js file. I have done a lot of reading and I have not been able to find a solution and was wondering if there is a way for me to have a split webpack config.
Any help would be much appreciated!
The error I am getting is:
ERROR in ./src/index.js 8:4
Module parse failed: Unexpected token (8:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render(
> <App title={title} />,
| document.getElementById('app')
| );
webpack 5.19.0 compiled with 1 error in 17 ms
i 「wdm」: Failed to compile.
My webpack config files:
webpack.common.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['#babel-loader'],
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, '..', './dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/index.html')
}),
],
devServer: {
contentBase: path.resolve(__dirname, '..', './dist'),
hot: true,
},
};
webpack.config.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
module.exports = ({ env }) => {
const envConfig = require(`./webpack.${env}.js`);
return merge(commonConfig, envConfig);
};
webpack.dev.js
module.exports = {
mode: 'development',
devtool: 'eval-source-map',
};
webpack.prod.js
module.exports = {
mode: 'production',
devtool: 'source-map',
};
My other files:
App.js
import React from "react";
const App = ({ title }) =>
<div>{title}</div>;
export default App;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hello World!</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<div id='app'></div>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "../App";
ReactDOM.render(
<App title={title} />,
document.getElementById('app')
);
module.hot.accept();
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
package.json
...
"scripts": {
"start": "webpack serve --config build-utils/webpack.dev.js --env env=dev",
"build": "webpack --config build-utils/webpack.prod.js --env env=prod",
"test": "echo \"Error: no test specified\" && exit 1"
},
...
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-cli": "^6.26.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.1",
"react-hot-loader": "^4.13.0",
"webpack": "^5.19.0",
"webpack-cli": "^4.4.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}

Unable to setup a webpack+react+jquery+bootstrap project

My project is compiled correctly. But I get this error in the console whenever I load the webpage :
bundle.4bc8d06487c51394a532.js:71 Uncaught Error: Module build failed: SyntaxError: Unexpected token (31:4)
[0m [90m 29 | [39m
[90m 30 | [39m[33mReactDOM[39m[33m.[39mrender(
[31m[1m>[22m[39m[90m 31 | [39m [33m<[39m[33mProvider[39m store[33m=[39m{createStoreWithMiddleware(reducers)}[33m>[39m
[90m | [39m [31m[1m^[22m[39m
[90m 32 | [39m [33m<[39m[33mApp[39m [33m/[39m[33m>[39m
[90m 33 | [39m [33m<[39m[33m/[39m[33mProvider[39m[33m>[39m
[90m 34 | [39m [33m,[39m document[33m.[39mquerySelector([32m'.container'[39m))[33m;[39m[0m
at Object.106 (bundle.4bc8d06487c51394a532.js:71)
at __webpack_require__ (bundle.4bc8d06487c51394a532.js:20)
at 106 (bundle.4bc8d06487c51394a532.js:63)
at bundle.4bc8d06487c51394a532.js:66
Here are my main files :
webpack.config.js
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const path = require('path')
const extractSass = new ExtractTextPlugin({
filename: "styles.css",
});
const VENDOR_LIBS = [
'react', 'lodash', 'redux', 'react-redux', 'react-dom', 'react-input-range', 'redux-form', 'redux-thunk'
];
module.exports = {
entry: {
bundle: './src/index.js',
vendor: VENDOR_LIBS
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
},
{
test: /\.(scss)$/,
use: extractSass.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: [{
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
})
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
loader: 'file-loader'
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery", // Used for Bootstrap JavaScript components
jQuery: "jquery", // Used for Bootstrap JavaScript components
Tether: 'tether',
Popper: ['popper.js', 'default'] // Used for Bootstrap dropdown, popup and tooltip JavaScript components
}),
extractSass
] };
.babelrc
{
"presets": ["babel-preset-env", "react"]
}
package.json
{
"name": "app-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"clean": "rimraf dist",
"build": "webpack",
"serve": "webpack-dev-server"
},
"repository": "",
"author": "Edgar KAMDEM",
"license": "ISC",
"dependencies": {
"bootstrap": "^4.0.0-alpha.6",
"file-loader": "^1.1.5",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-ui-dist": "^1.12.1",
"lodash": "^4.17.4",
"mxgraph": "^3.8.0",
"popper.js": "^1.12.9",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-input-range": "^1.2.2",
"react-redux": "^5.0.6",
"react-router": "^4.2.0",
"redux": "^3.7.2",
"redux-form": "^7.2.0",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"autoprefixer": "^7.1.6",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"node-sass": "^4.7.2",
"postcss-loader": "^2.0.9",
"precss": "^2.0.0",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.7"
}
}
index.js
// Bootstrap dependencies
window.$ = window.jQuery = require('jquery') // required for bootstrap
window.Popper = require('popper.js') // required for tooltip, popup...
import 'bootstrap'
// import '../scss/main.scss' import it in prod
import './index.scss' // include bootstrap css file with own modifications
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
// tooltip and popover require javascript side modification to enable them (new in Bootstrap 4)
// use tooltip and popover components everywhere
$(function (){
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').popover();
});
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>app test</title>
<link rel="stylesheet" type="text/css" href="build/styles.css">
<link rel="stylesheet" href="external/jqueryui-ruler/css/jquery.ui.ruler.css">
</head>
<body >
<header >
</header>
<!-- Begin page content -->
<div role="main" class="container">
</div>
<footer>
</footer>
<script src="build/bundle.4bc8d06487c51394a532.js"></script>
<script src="build/vendor.b97aa871a1eeaedf871a.js"></script>
</body>
</html>
app.js
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div style="font-size: 40px">React simple starter</div>
);
}
}
It's supposed to display "React simple starter" on the html page, but it doesn't.
Please help and let me know if you want to see other files
PS: I'm very new with webpack
Try adding babel-preset-env and babel-preset-react to your devDependencies and remove babel-preset-es2015:
yarn add -d babel-preset-env babel-preset-react or npm install -D babel-preset-env babel-preset-react
And change your .babelrc :
{
"presets": [
["react"],
["env"]
],
}
Edit:
Try creating your redux store like this:
const store = createStore(reducers) //assuming reducers is your combined reducers
...
<Provider store={store}>
Instead of :
const createStoreWithMiddleware = applyMiddleware()(createStore);
...
<Provider store={createStoreWithMiddleware(reducers)}>
The error in OP seems to indicate that the code from index.js ended up in encoded format in corresponding bundle. Are you sure the index.js is using proper characters on or after line with code const createStoreWithMiddleware = applyMiddleware()(createStore); ?

unexpected token < bundle js in reactjs app

i am creating js app from scratch , and this is my webpack config file
import path from 'path';
export default {
entry: path.join(__dirname,'/client/index.js'),
output: {
path: '/'
},
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname,'client'),
loaders: ['babel-loader'],
}
]
},
resolve: {
extensions: ['*', '.js']
}
}
this is my .babelrc file :
{
"presets": ["es2015", "react"]
}
this is my index.html file :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
this is my client/index.js
import React from 'react';
import { render } from 'react-dom';
import App from './Component/App';
render(<App />, document.getElementById("root"));
this is my App component
import React from 'react';
export default () => {
return <h1>Hello from react</h1>;
}
this is dependencies used by the app
{
"dependencies": {
"express": "^4.15.3",
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.11.0",
"webpack": "^3.2.0",
"webpack-dev-middleware": "^1.11.0",
"webpack-dev-server": "^2.5.1"
}
}
build is success but i got an error Unexpected token < bundle.js:1 after running the app,
anyone know what is causing the error? thank
Add filename to your webpack.config within output:
entry: path.join(__dirname,'/client/index.js'),
output: {
path: '/',
filename: 'bundle.js'
}
basically this is happening because in your index.html you are importing bundle.js
<script src="bundle.js"></script>
but your webpack is outputting index.js, by adding the filename attribute, webpack will now output bundle.js

Webpack unexpected token in JS file

I'm learning react and flux, and in lesson 1 the tutorial has failed me.
This tutorial immediately breaks on 'npm start' with the following errors:
ERROR in ./src/js/main.js
Module parse failed: /Users/me/Projects/egghead-flux/src/js/main.js Unexpected token (4:16)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (4:16)
at Parser.pp$4.raise (/Users/me/Projects/egghead-flux/node_modules/acorn/dist/acorn.js:2221:15)
It doesn't seem to understand ReactDOM.render(<App />, document.getElementById('main')); I assume parsing the JSX <App /> part is failing.
Has anyone encountered this issue before? Removing / reinstalling node modules does nothing. Is there some setup step missing from the video?
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
App.js
import React from 'react';
export default class App extends React.Component {
render(){
return <h1>Flux</h1>
}
}
webpack.config.js
module.exports = {
entry: './src/js/main.js',
output:{
path:'./dist',
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: '/\.jsx?$/',
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query:{
presets: ['es2015', 'react']
}
}
]
}
}
package.json
{
"name": "egghead-flux",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"flux": "^3.1.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-loader": "^6.2.7",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
Turns out:
test: '/\.jsx?$/',
should be:
test: /\.jsx?$/,
Dammit.

Unable to load ReactJS resource in the browser using Babel and Webpack

I'm trying to learn ReactJS by running a basic program.
webpack.config.js
var config = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.experts = config;
package.json
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
}
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
"Hello, world."
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script type="text/javascript" src = "index.js"></script>
</body>
</html>
On starting the server, I see an empty page with no contents. The HTML page is there but the part which is to be added to the DOM by React can't be seen.
index.js is set as the file which will contain our bundled app but the browser's console shows 'Faile to load resource index.js(404)' error. If I change the src attribute of script tag in HTML to main.js, I get a SyntaxError with the import statement.
I suspect the problem is with not correctly linking Babel or some other dependency with my package.
Inside webpack.config.js there is typo, must be exports instead of experts
module.exports = config;
^
in this case you don't export config from webpack.config.js, and webpack doesn't know about your custom configuration and uses default config.
I think the webpack.config.jswill be like
devtool: 'eval',
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
}],
}
and the <script>
<script type="text/javascript" src = "/static/bundle.js"></script>

Categories

Resources