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

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']
},

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"],
},
],
},
};

Webpack Source Map Export Compiled JS

I was using webpack 3, there was no hot reload issue and then I upgraded to webpack 5.
Webpack version: ^5.50.0, React version: 17.0.2
Webpack source map doesn't work properly. I attached a picture of output at the bottom.
When I read webpack documentation, there is no difference between my config with offical config.
Here is my webpack hot config for development;
const webpack = require('webpack') //to access built-in plugins
const HtmlWebpackPlugin = require('html-webpack-plugin') //installed via npm
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const vendorArray = require('./vendors')
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
main: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3002',
'webpack/hot/only-dev-server',
'./src/main.js'
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash:8].js'
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss', '.json']
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: './config/webpack/style-loader'
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', { targets: 'defaults' }], '#babel/preset-react'],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
[
'#babel/plugin-proposal-decorators',
{
legacy: true
}
]
]
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)([\?]?.*)$/,
type: 'asset/resource'
}
]
},
plugins: [
new webpack.DefinePlugin({
APP_ENV: JSON.stringify('dev')
}),
new HtmlWebpackPlugin({
template: './public/index.html',
templateParameters: {
recaptchaSiteKey: '6LfbRrEZAAAAAL1EiyUSq1yzEw1xqleak2xC2pzi',
intranetLogin: true
}
}),
new MiniCssExtractPlugin(),
new Dotenv({
path: path.resolve(__dirname, './../../.env.test')
})
]
}

How to import img from path by webpack 5?

I know this sounds ridiculous, but yes, I don't know how to import an img using webpack 5. What I want to do is just import an img which is located in the project folder and I want to import it into one of my react functional component and then to draw it on the <canvas> component.
My current webpack.config.js is as follow:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const outputDirectory = 'dist';
module.exports = {
entry: ['babel-polyfill', './src/client/index.js'],
output: {
path: path.join(__dirname, outputDirectory),
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
}
}, {
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
}, {
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: [{
loader: "url-loader",
options: {
limit: 100000
}
}, {
loader: "css-loader",
options: {
sourceMap: true
}
}]
}]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
port: 3000,
open: true,
historyApiFallback: true,
hot: true,
host: '0.0.0.0',
headers: {"Access-Control-Allow-Origin": "*"},
proxy: {
'/api': 'http://localhost:8080'
}
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html'
}),
new MiniCssExtractPlugin({
filename: "./css/[name].css"
})
]
};
The error message I got:
ERROR in ./public/floors.png 1:0
[1] Module parse failed: Unexpected character '�' (1:0)
[1] 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
[1] (Source code omitted for this binary file)
[1] # ./src/client/app/pages/WorkspaceGenerator.js 19:0-48 98:15-18
[1] # ./src/client/app/App.js 19:0-60 66:42-60
[1] # ./src/client/index.js 2:0-28 4:35-38
[1]
[1] webpack 5.38.1 compiled with 1 error in 589 ms
[1] ℹ 「wdm」: Failed to compile.
The hierarchy of the project I'm working on:
but you know what? I really don't know where to start to find the resource to do that, there are just too many things on their website written in a non-human-readable way! Please help!
Problem
You've included css-loader as a use rule for png|woff|woff2|eot|ttf|svg assets, however css-loader doesn't handle image assets. Please remove it as a rule for that particular test and either only use url-loader or file-loader.
Solution
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const outputDirectory = "dist";
module.exports = {
entry: ["babel-polyfill", "./src/client/index.js"],
output: {
path: path.join(__dirname, outputDirectory),
filename: "bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
["#babel/preset-react", { runtime: "automatic" }],
],
},
},
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: "url-loader", // "file-loader"
options: {
limit: 100000,
},
},
],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
devServer: {
port: 3000,
open: true,
historyApiFallback: true,
hot: true,
host: "0.0.0.0",
headers: { "Access-Control-Allow-Origin": "*" },
proxy: {
"/api": "http://localhost:8080",
},
disableHostCheck: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "./public/index.html",
}),
new MiniCssExtractPlugin({
filename: "./css/[name].css",
}),
],
};
Result

Webpack Dev Server (Uncaught SyntaxError: Unexpected token '<' )

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",
}),
]
}

Webpack - "css-loader/locals" miss matched for server.build and client.build

I setup a webpack config to build server.build and client.build, but they both producing different css/locals.
webpack.server.js
const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const serverConfig = {
name: 'server',
target: 'node',
externals: [nodeExternals()],
entry: [
__dirname+'/index.js'
],
output: {
path: path.join(__dirname, '/.build'),
filename: 'server.build.js',
publicPath: '.build/',
libraryTarget: 'commonjs2'
},
module: {
loaders: [
{
test:/\.(?:js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(?:css|less)$/,
use: "css-loader/locals?import=1&modules=1&localIdentName=[name]__[local]__[hash:base64:7]",
exclude: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/,
loader: 'url-loader?limit=1000&name=./fonts/[name].[ext]?[hash:base64:5]#icomoon',
}
]
},
resolve: {
extensions: ['.jsx', '.js', '.json','.less']
}
};
module.exports = serverConfig;
webpack.client.js
const webpack = require('webpack');
const path = require('path');
const context = path.resolve(__dirname, 'src');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
name:"client",
context,
entry: __dirname+'/src/app.js',
output: {
path: __dirname+"/.build/assets",
filename: 'bundle.js'
},
devtool: "source-map",
module: {
rules: [
{
test:/\.(?:js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(?:css|less)$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader?module',
options: {
sourceMap: true,
importLoader: true,
localIdentName:'[name]__[local]__[hash:base64:7]'
}
},
{
loader: 'less-loader',
options: {
sourceMap: true,
importLoader: true,
}
}
],
fallback: 'style-loader',
}),
exclude: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/,
loader: 'url-loader?limit=1000&name=./fonts/[name].[ext]?[hash:base64:5]#icomoon',
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'bundle.css',
allChunks: true,
}),
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true),
NODE_ENV: JSON.stringify("production")
}
}),
],
resolve: {
extensions: ['.jsx', '.js', '.json']
}
};
module.exports = config;
Ex: server.build.js -> style__cont__2KTI-wF
bundle.js/bundle.css (client) -> style__cont__58B3ts_
I am really stuck at this point, i am new to react and there is no perfect approach to import css server side.

Resources