How to import img from path by webpack 5? - reactjs

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

Related

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

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

React app looking for bundle.js in component folder not project root

The errors I get below are shown in the console after I refresh on a nested route (register/email-confirmation). Whereas non-nested routes do not get this error.
I think the main problem is that it's searching for bundle.js and the image in the nested route path, as opposed to the root path.
The errors in my console:
GET http://localhost:3002/register/bundle.js net::ERR_ABORTED
Refused to execute script from 'http://localhost:3002/register/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
GET http://localhost:3002/register/a5e694be93a1c3d22b85658bdc30008b.png 404 (Not Found)
My webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BUILD_PATH = path.resolve( __dirname, "./client/build" );
const SOURCE_PATH = path.resolve( __dirname, "./client/src" );
const PUBLIC_PATH = "/";
...
module.exports = {
devtool: 'eval-source-map',
context: SOURCE_PATH,
entry: ['babel-polyfill', SOURCE_PATH + '/index.jsx'],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/, /server/],
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'react', 'stage-1', 'stage-0', 'stage-2'],
plugins: [
'transform-decorators-legacy',
'transform-es2015-destructuring',
'transform-es2015-parameters',
'transform-object-rest-spread'
]
}
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
],
},
output: {
path: BUILD_PATH,
filename: "bundle.js",
},
devServer: {
compress: true,
port: 3002,
historyApiFallback: true,
contentBase: BUILD_PATH,
publicPath: PUBLIC_PATH,
},
plugins: [
new webpack.DefinePlugin(appConstants),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'client/src/index.html'),
inject: true
}),
],
watch: true,
}
I don't know about this bug, but I highly recommend using fuse-box
fuse-box is the future of the build systems, within few minutes you will be running your project with high speed hot reload and many others utitilites...
check this react example seed, it's incredibly amazing..

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.

PostCSS Module Parse Failed on Windows 10 build

I'm running into an interesting error with my react build. My configuration runs perfectly fine on my Mac, but I get the following error when running on my Windows 10 computer:
ERROR in ./~/react-toolbox/lib/app_bar/theme.css
Module parse failed: C:\cygwin64\home\username\projectname\node_modules\react-toolbox\lib\app_bar\theme.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| :root {
| --palette-red-50: rgb(255, 235, 238 );
| --palette-red-100: rgb(255, 205, 210);
# ./~/react-toolbox/lib/app_bar/index.js 16:13-35
# ./src/containers/app/app.js
# ./src/index.js
# multi react-hot-loader/patch ./src/index.js
Here's my Webpack 2 Config
'use strict'
const webpack = require('webpack')
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const postcssImport = require('postcss-import')
const postcssCssnext = require('postcss-cssnext')
// configure source and distribution folder paths
const publicFolder = 'public'
const buildFolder = 'build'
module.exports = {
entry: {
'app': [
'react-hot-loader/patch',
'./src/index.js'
]
},
resolve: {
//Allows us to leave off the file extension when importing
extensions: ['.js', '.json', '.jsx']
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
exclude: '/node_modules/',
loader: 'eslint-loader',
},
{
test: /\.(js|jsx)$/,
exclude: '/node_modules/',
loader: 'babel-loader'
},
{
test: /\.css$/,
include: [
/(node_modules)\/react-toolbox/,
path.join(__dirname, 'src')
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: 'inline',
plugins: function() {
return [
postcssImport({ addDependencyTo: webpack }),
postcssCssnext({
browsers: ['last 2 versions', '> 5%'],
compress: true,
})
]
},
},
}
]
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: '[name].bundle.css',
allChunks: true
}),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'index.html'),
to: path.join(__dirname, buildFolder, 'index.html')
}]),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'demo.html'),
to: path.join(__dirname, buildFolder, 'demo.html')
}]),
new CopyWebpackPlugin([{
from: path.join(__dirname, publicFolder, 'demo.js'),
to: path.join(__dirname, buildFolder, 'demo.js')
}]),
new webpack.NamedModulesPlugin()
],
output: {
path: path.resolve(__dirname, buildFolder),
filename: '[name].js',
publicPath: '/'
},
devtool: 'eval',
devServer: {
// files are served from this folder
contentBase: path.join(__dirname, 'build'),
// support HTML5 History API for react router
historyApiFallback: true,
// listen to port 5000, change this to another port if another server
// is already listening on this port
port: 5000,
//match the output 'publicPath'
publicPath: '/',
//Proxies to match requests to our Django API endpoints
proxy: {
'/api': {
target: 'http://localhost:4000'
}
},
hot: true
}
}
And for good measure, here's my .babelrc config
{
"presets": [
[ "es2015", { "modules": false } ],
"latest",
"react"
],
"plugins": ["react-hot-loader/babel", "syntax-dynamic-import"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
No idea why the error occurs when compiling on Windows 10 but works perfectly on my Mac. I can't seem to find any current info regarding this issue for either PostCSS or Webpack 2.
Any ideas?
just remove
include: [
/(node_modules)\/react-toolbox/,
path.join(__dirname, 'src')
]
from test: /\.css$/ rule

Resources