Webpack Dev Server (Uncaught SyntaxError: Unexpected token '<' ) - webpack-dev-server

Building TS/SASS with Webpack works fine, running this through VSCode Live Server plugin renders the index.html perfectly to the app folder.
Running webpack-dev-server with it looking at the same app folder does not. The page opens but there is a Javascript error Uncaught SyntaxError: Unexpected token '<'
And the page does not render the JS/CSS.
webpack.config.js
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
open: 'http://localhost',
port: 80,
publicPath: path.resolve(__dirname, 'app'),
hot: true
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
tsconfig.json
{
"compilerOptions": {
"sourceMap": true
}
}
main.ts
console.log('Main.ts has loaded')
import './styles/main.scss'
Any help with this would be appreciated, I'm losing my mind lol.

My issue was with syntax in the webpack.config.js file.
I was neglecting to insert a comma at the end of the last entry in every object and array, believing it not to be necessary.
Here is a working config:
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app'),
},
devServer: {
open: 'http://localhost',
port: 80,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
}

Related

Webpack Error - You may need an appropriate loader to handle this file type,

I was trying to add webpack config in my react project, but i am facing issue as when i run the project , i get an error which says -
ERROR in ./src/index.js 14:2
Module parse failed: Unexpected token (14:2)
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(
> <React.StrictMode>
| <App/>
| </React.StrictMode>,
here below is my configuration for webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin(),
],
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader, // instead of style-loader
"css-loader",
],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: ["file-loader"],
},
{
test: /\.svg$/,
use: ["file-loader"],
},
],
},
};
Your configuration has 2 module keys. They conflict with each other. Merging them should resolve your issue:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin(),
],
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader, // instead of style-loader
"css-loader",
],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: ["file-loader"],
},
{
test: /\.svg$/,
use: ["file-loader"],
},
],
},
};

Can I optimize my webpack config so my production file size gets reduced even more?

I have spent days getting to my current Webpack configuration setup.
When Webpack runs the build, the file size of my minified output file "react_customer.uniqueid.js" ends up being 2.53 MB, I would be satisfied if the file size would be under 1 MB.
Here is a visualization of the bundled JavaScript.
Could this setup be optimized further so the file size gets reduced?
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const { EnvironmentPlugin } = require("webpack");
module.exports = {
mode: "production",
entry: {
react_customer: path.resolve(__dirname, "react-customer/index.js"),
react_admin: path.resolve(__dirname, "react-admin/index.js"),
},
output: {
path: path.resolve(__dirname, "production-build"),
filename: "[name].[contenthash].js",
assetModuleFilename: "[name][ext]",
clean: true,
publicPath: "/",
},
//externals: [nodeExternals()],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
// `terserOptions` options will be passed to `uglify-js`
// Link to options - https://github.com/mishoo/UglifyJS#minify-options
terserOptions: {},
}),
],
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, /*"style-loader",*/ "css-loader"],
},
{ test: /\.(svg|ico|png|webp|jpg|gif|jpeg)$/, type: "asset/resource" },
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
["#babel/preset-env", { modules: false }],
["#babel/preset-react", { runtime: "automatic" }],
],
},
},
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
//"style-loader",
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
plugins: [
new EnvironmentPlugin({
backend_server: "https://www.example.com",
frontend_customer: "https://www.example.com",
}),
new BundleAnalyzerPlugin(),
new MiniCssExtractPlugin(),
new HtmlWebpackPlugin({
filename: "index.html",
template: path.resolve(
__dirname,
"server/templates/other/react-customer-template.html"
),
chunks: ["react_customer"],
}),
new HtmlWebpackPlugin({
filename: "admin.html",
template: path.resolve(
__dirname,
"server/templates/other/react-admin-template.html"
),
chunks: ["react_admin"],
}),
],
};

Webpack5 config error: An appropriate loader to handle this file type

I'm trying to migrate webpack4 to webpack5. My project has both react and typescript files.
I'm running into below error:
ERROR in ./src/index.js 19:4
Module parse failed: Unexpected token (19: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(
> > <Provider store={store}>
> | <App/>
> | </Provider>
,
webpack 5.11.1 compiled with 1 error in 67 ms
webpack.common.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const moment = require('moment');
const CircularDependencyPlugin = require('circular-dependency-plugin');
module.exports = (...args) => {
const [
env,
{ configName }
] = args;
return {
entry: ['#babel/polyfill', './src/index.js'],
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: './index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[name].[chunkhash].css',
}),
new webpack.DefinePlugin({
__SNAPSHOT__: JSON.stringify(moment().format('MMMM Do YYYY, h:mm:ss a')),
__MODE__: JSON.stringify(env),
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: true,
allowAsyncCycles: false,
cwd: process.cwd(),
})
],
output: {
path: path.resolve(__dirname, 'build'),
chunkFilename: '[name].[chunkhash].js',
filename: '[name]_bundle.js',
publicPath: '/build/',
chunkLoading: false
},
target: ['web'],
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(sa|sc)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: env === 'development',
},
},
'css-loader',
'postcss-loader',
'sass-loader',
]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['url-loader']
}
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
port: 8888
}
}
};
try it removing:
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},

bundle.js not found with webpack dev server

I'm having an issue with React/Redux/Webpack/Router.
Any "sub pages", such as: "/home/test", "users/registration" etc... fail to be loaded - and I get errors loading the "bundle.js" file generated by webpack.
The reason seems to be that the request to fetch the "bundle.js" is with the following url:
for path "/home/test": "/home/bundle.js"
for path "/users/registration": "/users/bundle.js"
Same issue occurs with the loading of "css" files and other resources.
This is my webpack configuration:
const { resolve } = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const config = {
devtool: 'cheap-module-eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./main.js',
//'./assets/scss/main.scss',
],
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
publicPath: '/',
},
context: resolve(__dirname, 'src'),
devServer: {
hot: true,
contentBase: resolve(__dirname, 'build'),
publicPath: '/',
historyApiFallback: true
},
module: {
rules: [
/* {
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "eslint-loader"
}, */
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader',
],
exclude: /node_modules/,
},
{
test: /\.(scss|sass)$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
publicPath: '../'
}),
},
{ test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=15000&name=images/[name].[ext]' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
{ test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
test: /\.js$/,
options: {
eslint: {
configFile: resolve(__dirname, '.eslintrc'),
cache: false,
}
},
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({ filename: './styles/style.css', disable: true, allChunks: true }),
new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
new webpack.HotModuleReplacementPlugin(),
],
};
module.exports = config;
It seems as if it always uses "../bundle.js" to find it for some reason.
Any help would be appreciated :)
Thank you,

React, WebPack and Babel for Internet Explorer 10 and below produces SCRIPT1002: Syntax error

I've read multiple threads regarding similar issues and tried some propositions, but had no results.
I've followed few tutorials related to React.js and WebPack 3. As the result the application is working well on all browsers (at this moment) except IE 10 and below. The error points to bundle.js (once I'm using the configuration Nr.1):
SCRIPT1002: Syntax error and the line - const url = __webpack_require__(83);
With configuration Nr2., on local server - : SCRIPT1002: Syntax error - line with eval()
And the same configuration, but running on remote server produces a bit different error:
SCRIPT5009: 'Set' is undefine
WebPack configuration Nr1.:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.json$/,
exclude: /node_modules/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
],
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
}
]
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
plugins: [HtmlWebpackPluginConfig]
}
WebPack configuration Nr2.:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
module.exports = {
stats: {
warnings: false
},
devtool: 'cheap-eval-source-map',
devServer: {
historyApiFallback: true,
contentBase: './'
},
entry: {
app: path.resolve(sourcePath, 'index.js')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks: Infinity
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
path: buildPath,
excludeChunks: ['base'],
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new webpack.NoEmitOnErrorsPlugin(),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react', 'es2015'],
plugins: ["transform-es2015-arrow-functions"]
}
},
include: sourcePath
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: true } },
'postcss-loader',
'sass-loader'
]
})
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
Here additionally I've added the es2015 to presets: ['env', 'react', 'es2015'] and plugins: ["transform-es2015-arrow-functions"] but it made no sense.
Well in case when the babel loader won't work at all of misconfiguration or something else, I think that the whole application won't start. I believe that something should be done with presets or their order... Need advice from experienced developer
UPDATE
I've changed devtool to inline-cheap-module-source-map and got error point to overlay.js -> const ansiHTML = require('ansi-html');
In your package.json file
change the version of webpack-dev-server to version "2.7.1" (or earlier).
"webpack-dev-server": "2.7.1"
Then do a npm install et voilĂ .
That solved the problem for me.
All versions after 2.7.1 gives me an error similar to yours.
Simply add devtools : "source-map" to your Webpack config like this:
const path = require('path');
module.exports = {
devtool: "source-map",
entry: ['babel-polyfill', path.resolve(__dirname, './js/main.js')],
mode: 'production',
output: {
path: __dirname+'/js/',
filename: 'main-webpack.js'
}
};
This will remove eval and change your source map to be supported by IE.
UPDATE I've changed devtool to inline-cheap-module-source-map and got error point to overlay.js -> const ansiHTML = require('ansi-html');
And to support ES6 syntax you have to compile your JavaScript code with Babel.

Resources