webpack producing Uncaught SyntaxError: Unexpected token < bundle.js:1 - javascript

I'm a bit confused on what this issue may be. I've deleted bundle.js thinking by creating a new one would resolve the issue (Someone stated it in a different question), but that didn't happen. The error I'm getting is
Uncaught SyntaxError: Unexpected token < bundle.js:1
which points to
<!DOCTYPE html>
I've seen other forms people mentioning this error is to do with a 404 return of the html file. I was hoping someone can tell me if my webpack output is wrong. Within my html file I have
<script type="text/javascript" src="../src/javascripts/bundle.js"></script>
and my webpack is
let path = require("path");
let webpack = require("webpack");
module.exports = {
context: path.join(__dirname, "src"),
entry: "./index.js",
module: {
rules: [
{
test: [/\.jsx?$/, /\.js?$/],
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["react", "env"],
plugins: ["emotion"]
}
}
},
{
test: [/\.scss$/, /\.css$/],
use: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.svg$/,
loader: "svg-inline-loader"
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
"file-loader",
{
loader: "image-webpack-loader",
options: {
bypassOnDebug: true,
disable: true
}
}
]
},
{
test: /\.csv$/,
loader: "csv-loader",
options: {
dynamicTyping: true,
header: true,
skipEmptyLines: true
}
},
{
test: /\.ttf$/,
use: [
{
loader: "ttf-loader",
options: {
name: "./font/[hash].[ext]"
}
}
]
}
]
},
resolve: { extensions: [".js", ".jsx", ".scss", ".png"] },
output: {
path: __dirname + "/src/javascripts",
filename: "bundle.js"
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("production")
})
]
};
If someone has seen this before and found a solution to it. I would love to learn why it has occurred and how to avoid this in the future.
Thank you again for all the help and teaching.
[UPDATE]
Here is an image of the error and what it shows when I click on bundle.js:1
Image showing error
Image under is my network
Network
[UPDATE!!!]
I've been wondering how come I'm seeing two bundle and notice the one within the body has a wrong path. Does anyone know where this came from? I don't see it in mny html file. This is an image of it
enter image description here

You may have referenced a local js or ts file in your html page that does not exist on disk.
<script src="doesThisFileExist.js"></script>

Related

Adding style guide to next.js (react) returns Error: ENOENT: no such file or directory,

I just started learning next.js and I wanted to add some documentation using https://react-styleguidist.js.org/
I created my project using npx create-next-app
After installing it, and adding some configuration
[styleguide.config.js]
const path = require('path')
module.exports = {
components: './**/*.js',
webpackConfig: {
entry: 'next/lib/app.js',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['#babel/react' ],
plugins: ['#babel/plugin-proposal-class-properties']
}
}
},
{
test: /\.scss$/,
loader: 'sass-loader'
}
]
}
}
};
I'm getting the following error when trying to run it using the following command:
npx styleguidist server
./node_modules/react-styleguidist/lib/client/index.js (./node_modules/react-styleguidist/lib/loaders/styleguide-loader.js!./node_modules/react-styleguidist/lib/client/index.js)
Error: ENOENT: no such file or directory, scandir '${projectPath}\node_modules\ally.md\amd'
at Array.map (<anonymous>)
at Array.map (<anonymous>)
# ./node_modules/react-styleguidist/lib/client/index.js 36:19-71 46:2-49:4 46:65-49:3
# multi ./node_modules/react-styleguidist/lib/client/index ./node_modules/react-dev-utils/webpackHotDevClient.js
(Note that I have replaced the project path for "${projectPath}")
And I'm at a loss on how to fix it.
For further details, you can find my package.json here https://pastebin.com/H7RfxxKZ.
My folder structure shown in below image:
All my components are under src/components, some include component.module.css files
My context components are under src/context
All my global scss can be found under "styles/"
Any guidance on why this can happen and how to solve it would be appreciated, my knowledge on how the configuration files work is limited, and any reference to any related article would be appreciated.
Thanks for your help. have a nice rest of the day and stay safe.
After doing some further testing, I found out that my main problem was the "components: './**/*.js'" and the fact that I was missing some alias for my components! I will post here what worked for me.
module.exports = {
components: "./src/**/*.js",
skipComponentsWithoutExample: true, //You don't need this one
moduleAliases: { //Map it to your folder structure
'components': path.resolve(__dirname, 'src','components'),
'_db': path.resolve(__dirname, 'src','_db'),
'context': path.resolve(__dirname, 'src','context'),
'styles': path.resolve(__dirname, 'src','styles'),
},
webpackConfig: {
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.scss$/,
loaders: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{ //This code prevents errors with font-awesome
test: /\.(ttf|eot|svg|gif|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [{
loader: 'file-loader',
}]
},
],
},
},
};

Invalid or unexpected token loading css file using webpack in react project

I have a react project that uses styled components, and I'm trying to include a CSS file as part of react-image-gallery
I followed the steps to include css-loader and style-loader in my project and tried importing the file like this
import 'react-image-gallery/styles/css/image-gallery.css
and included the following in Webpack config rules
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
When running the server I'm getting the below error message
SyntaxError: Invalid or unexpected token
(function (exports, require, module, __filename, __dirname) { #charset "UTF-8";
in the above CSS file
From some googling, I understood that this is because the CSS file is included as a JS file by Webpack. But isn't that how it is supposed to be?
Addition info: I have a server side rendered app.
What am I doing wrong?
Update:
My rules look like this
A rules.ts file
import webpack from 'webpack'
const ts: webpack.RuleSetRule = {
test: /^(?!.*\.spec\.tsx?$).*\.tsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}
const img: webpack.RuleSetRule = {
test: /\.(png|jpe?g|gif|svg)$/,
use: 'file-loader',
}
const css: webpack.RuleSetRule = {
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
export default {
client: {
ts,
img,
css,
},
server: {
ts,
css,
img: { ...img, use: [{ loader: 'file-loader', options: { emitFile: false } }] },
},
}
A config file that has the following
const config: webpack.Configuration = {
context: path.join(__dirname, '../../src/client'),
resolve: {
...resolve.client,
alias: { 'react-dom': '#hot-loader/react-dom' },
},
devtool: false,
entry: {
main: ['./index.tsx'],
},
mode: 'development',
module: {
rules: [rules.client.ts, rules.client.img, rules.client.css],
},
output: output.client,
plugins: [
...plugins,
...developmentPlugins,
new ForkTsCheckerWebpackPlugin({
tsconfig: path.join(__dirname, '../../tsconfig.fork-ts-checker-webpack.plugin.json'),
}),
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['!webpack.partial.html', '!favicon.ico'],
}),
],
}
We had 4 co-workers stuck on an issue like that.
Actually, we had a plugin "nodemon-webpack-plugin", which we configured for webpack.
This plugin tried to execute files like .css as java-script files.
We finally removed this plugin, because we had an up and running mon already.

Javascript File Not Found in Browser but Compiles Correctly

I went through a React Introduction found on Microsoft Virtual Academy and downloaded the code found in the associated GitHub repo. At this point I'm just trying to have my simple Index.html page create an empty React Div Tag.
However i'm having trouble establishing my environmentI installed node.js, downloaded the start code from github, did my npm install and upon compile got the error "Breaking Change: Its's not longer allowed to omit the '-loader' when using loaders. You need to specify the file-loader instead of file. I fixed this error by changing the webpack.config.js .html loader under module from "file?name=[name].[ext]" to "file-loader?name=[name].[ext]".
However upon doing that I received an error stating "Conflict: Multiple assets emit to the same filename" error when compiling. I fixed this error by changing the output filename in the webpack.config.js from bundle.js to [name].js.
Then it compiled fine but when looking at it in the browser I noticed that there was an error stating "the server has not found anything matching the requested URI" and mentions app.js.
I have tried changing the call in my Index.html to app.js but also get the same error. I have tried clearing out the code in my app.js so it is completely empty and still get the requested URI error. Below is my very simple code...
webpackag.config.js`var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.join(__dirname, 'app'),
entry: {
javascript: './app.js',
html: './index.html'
},
  output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
  module: {
    loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.html$/,
loader: "file-loader?name=[name].[ext]",
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
}
]
  },
devServer: {
historyApiFallback: true
}
};
Code for Index.html...`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pizza Bot Manager</title>
<link rel="stylesheet" href="/app/app.css">
</head>
<body>
<div id="main">
</div>
<script src="./app.js"></script>
</body>
</html>
App.Js code below...
var React = require('react');
var ReactDom = require('react-dom');
var App = React.createClass({
render: function() {
return (
<div>
</div>
)
}
});
ReactDOM.render(<App />, Document.getElementById("main"));
`
Very new to React so if anyone has any suggestions on how to resolve this error I would really appreciate it
Error as it appears in the Browser Console
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
GET - http://localhost:8080/app.js
OK looks like adding brackets around my input files in the webpack.config.js seemed to resolve the 404 error. See updated "entry" code below for resolution to help others who may have this issue...
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.join(__dirname, 'app'),
/*entry: {
html: './index.html',
javascript: './app.js'
},*/
entry: ['./index.html','./app.js'],
  output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
  module: {
    loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.html$/,
loader: "file-loader?name=[name].[ext]",
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
}
]
  },
devServer: {
historyApiFallback: true
}
};

can't put breakpoins on javascript

I'm debugging a javascrip code in chrome, but the chrome doesn't let me put breakpoints where I want. I click to put the breakpoint and he puts it some lines before or after the line that a clicked.
I click the line 94, and he puts a break in line 96.
the code in chrome
what do I do to debug it?
some help please.
Down here is the webpack.config.development.js
import path from 'path';
import webpack from 'webpack';
import validate from 'webpack-validator';
import merge from 'webpack-merge';
import formatter from 'eslint-formatter-pretty';
import baseConfig from './webpack.config.base';
const port = process.env.PORT || 3000;
export default validate(merge(baseConfig, {
debug: true,
devtool: 'eval-source-map',
entry: [
`webpack-hot-middleware/client?
path=http://localhost:${port}/__webpack_hmr`,
'babel-polyfill',
'./app/styles/main.less',
'./app/index'
],
output: {
publicPath: `http://localhost:${port}/dist/`
},
resolve: {
fallback: path.join(__dirname, 'node_modules')
},
resolveLoader: { fallback: path.join(__dirname, 'node_modules') },
module: {
loaders: [
{
test: /\.(less|scss)$/,
loader: 'style!css!autoprefixer!less'
},
// Load images
{ test: /\.jpg/, loader: 'url-loader?limit=10000&mimetype=image/jpg' },
{ test: /\.gif/, loader: 'url-loader?limit=10000&mimetype=image/gif' },
{ test: /\.png/, loader: 'url-loader?limit=10000&mimetype=image/png' },
{ test: /\.svg/, loader: 'url-loader?limit=10000&mimetype=image/svg' },
// Load fonts
{ test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?
limit=10000&mimetype=application/font-woff' },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-
loader' },
]
},
eslint: {
formatter
},
plugins: [
// https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
new webpack.HotModuleReplacementPlugin(),
// “If you are using the CLI, the webpack process will not exit with an error code by enabling this plugin.”
// https://github.com/webpack/docs/wiki/list-of-plugins#noerrorsplugin
new webpack.NoErrorsPlugin(),
// NODE_ENV should be production so that modules do not perform certain development checks
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
// https://github.com/chentsulin/webpack-target-electron-renderer#how-
this-module-works
target: 'electron-renderer'
}));
Use the debugger; statement in your code where you want it to pause, if you know where you want to put the breakpoints before running the code.
Make sure the console is open before debugging, because otherwise the breakpoints will be disabled.

webpack-dev-server acting weird

I've encountered a problem working with webpack-dev-server wherein the terminal output states that the bundle is valid, and when I request my app on my server (ie localhost), everything works as it should. When I request my app from another host, however, I am unable to load bundle.js, and I get a Network connection was lost error on Safari and a net::ERR_EMPTY_RESPONSE on Chrome. To explain further, if I go to http://url/public/bundle.js on my server, I get bundle.js, and if I try to do the same on my local machine, I get the errors. Here's my webpack.config.js file:
module.exports = {
entry: [
'./assets/jsx/modsoussi.jsx'
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: 'http://modsoussi.xyz:8080/public/',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015','react'] // react preset is needed in this case to avoid
// unexpected token '<' error.
}
}
]
},
externals: {
'react':'React'
},
resolve: {
extensions: ['','.js','.jsx']
}
}

Categories

Resources