how to load image react babel - reactjs

I'm loading icons on my app.js
import bg from './icons/bg.png';
import br from './icons/br.png';
import rg from './icons/rg.png';
import ig from './icons/invert.png';
import bw from './icons/bw.png';
import by from './icons/by.png';
import gm from './icons/gm.png';
import rs from './icons/rs.png';
They work fine when i run the default react start script, but when i try to compile using this webpack:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/js/index.js',
devtool: 'inline-source-map',
target: 'electron-renderer',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [[
'#babel/preset-env', {
targets: {
esmodules: true
}
}],
'#babel/preset-react']
}
}
},
{
test: [/\.s[ac]ss$/i, /\.css$/i],
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
}
]
},
resolve: {
extensions: ['.js'],
},
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'build', 'js'),
},
};
I get this errors for each image:
ERROR in ./src/js/icons/bg.png 1:0
Module parse failed: Unexpected character '�' (1:0)
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
(Source code omitted for this binary file)
# ./src/js/App.js 2:0-32 230:9-11
# ./src/js/index.js 4:0-24 5:107-110
Which provably means that babel is trying to load the image as a javascript file, is there a way to load a image on React when compiling it with Babel?

As mentioned in webpack docs
Out of the box, webpack only understands JavaScript and JSON files.
So you need to use loader for png file as webpack don't know what to do with that file.
file-loader
More on Loaders

Related

Trying to parse Tailwind .css file and encountering Module parse failed: Unexpected character '#' (1:0)

I'm completely new to Tailwind, React, and Webpack. I've been trying to get them to work together, but I'm having trouble parsing the main CSS file that has the Tailwind directives.
On execution of my script, I'm getting this error:
ERROR in ./static/index.css 1:0
Module parse failed: Unexpected character '#' (1:0)
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
I've tried finagling with css-loader, postcss-loader, etc. to no avail.
"App.js"
import React from "react"
function App() {
return <div className="bg-slate-900 h-screen">Hello, Tailwind!</div>
}
export default App
"index.js"
import React from 'react';
import ReactDOM from 'react-dom'
import App from "./js/App"
import "./index.css"
ReactDOM.render(
<App />,
document.getElementById('root')
);
"webpack.config.js"
const path = require('path');
module.exports = {
entry: './static/index.js', // path to our input file
output: {
filename: 'index-bundle.js', // output bundle file name
path: path.resolve(__dirname, './static'), // path to our Django static directory
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, './static'),
exclude: /node_modules/,
loader: "babel-loader",
options: { presets: ["#babel/preset-env", "#babel/preset-react"] }
},
{
test: /\.css$/i,
include: path.resolve(__dirname, './static'),
use: ['style-loader', 'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: ["postcss-preset-env",],
},
},
},
],
},
]
},
devServer: {
static: 'dist',
watchContentBase: true,
},
};
I not sure of the answer but I think that you could either read through the set up process and see if you missed something or you could just re do it :)
https://tailwindcss.com/docs/guides/create-react-app

Webpack Module parse failed with bootstrap css

I'm trying to build with webpack
npm run build
But I get the following error
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.min.css 1:0
Module parse failed: Unexpected character '#' (1:0)
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
#charset "UTF-8";/*!
| * Bootstrap v5.0.2 (https://getbootstrap.com/)
| * Copyright 2011-2021 The Bootstrap Authors
My webpack config looks like this
const path = require("path");
module.exports = {
mode: "production",
entry: "./paginate.js",
output: {
path: path.resolve("./"),
filename: "index.js",
libraryTarget: "commonjs2",
},
module: {
rules: [
{
test: /\.js|jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
}
],
},
externals: {
react: "react",
},
};
.babelrc file looks like
{
"presets": ["#babel/preset-env", ["#babel/preset-react", {
"runtime": "automatic"
}]]
}
I've searched but can't seem to find the right loader for this.
I'm not sure, just a guess, most likely bootstrap is trying to import CSS or scss and you don't have a loader for it defined.
Try adding:
{
test: /\.s?[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: [/node_modules/],
},
To your webpack rules and also install those modules with --save-dev.
Side node, this regular exression test: /\.js|jsx?$/, is incorrect, just use test: /\.jsx?$/,. The "?" means the x is optional.

Error while importing font or images file inside scss using Webpack 4 and react js

I am using webpack and react js.
I am getting this error when i try to import image or font file inside my scss file.
I have tried many solutions but none of them solved my problem,
webpack.common.js
enter image description here
const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js",
vendor: "./src/vendor.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(ttf|svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
Here is another webpack.dev.js
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader" //1. Turns sass into css
]
}
]
}
});
ERROR in ./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss)
Module not found: Error: Can't resolve '../../../src/assets/fonts/icomoon.ttf' in 'C:\Users\jamal\Documents\webpack-demo-app\src\assets'
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
You need to remember that the import actually takes "place" from the root index.scss file (the one that loads all the other partials). So the path you are using to fetch the asset is not accurate.
You need to use ./fonts/icomoon.ttf instead of ../fonts/icomoon.ttf
your file structure:
assets/
------/fonts
------/images
------/sass
------/---/partial1.scss // while the reference to the image is here
------/index.scss // the actual root of the reference call is here

Webpack: Can I get a source map for after babel, before minification?

I have a fairly basic webpack setup that runs babel and out comes my minified js with a source map.
Now when I run my source map in chrome I get the js before babel and before minification. However I would often like to have my source map after babel but before minification. Is this possible?
TL;DR I want source map to post-babel pre-minifcation. Possible?
For completeness
I run babel-loader 8 with webpack 4
Here is a screenshot from chrome showing the problem. As you can see the Dropzone tag indicates this is jsx (and so before babel)
Secondly here is my webpack config (not that it actually matters for my question).
const path = require('path');
module.exports = {
context: path.join(__dirname, 'Scripts', 'react'),
entry: {
client: './client'
},
output: {
path: path.join(__dirname, 'Scripts', 'app'),
filename: '[name].bundle.min.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
plugins: [require('#babel/plugin-proposal-object-rest-spread')],
presets: ["#babel/es2015", "#babel/react", "#babel/stage-0"]
}
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
externals: {
// Use external version of React (from CDN for client-side, or
// bundled with ReactJS.NET for server-side)
react: 'React'
},
devtool: 'source-map'
};
Running webpack with -d gives a second set of source maps in chrome that does the trick.

Webpack loader fails when importing .css in react_on_rails app?

I am trying to use react-datetime on my react-on-rails app. To make the datetime work out of the box, I need to import the CSS mentioned on their GH page.
On my app, I copy/paste the CSS into a file I named DateTime.css:
...
import DateTime from 'react-datetime';
import '../../schedules/stylesheets/DateTime.css';
...
export default class AddDate extends React.Component {
But it gives me this error:
VM45976:1 Uncaught Error: Module parse failed: /Users/some/path/to/my/project/App/components/schedules/stylesheets/DateTime.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| .rdt {
| position: relative;
| }
It seems like the CSS loader is not working. I tried this on pure react app (create-react-app) and it worked. It broke when I did it inside react_on_rails.
This is my webpack config atm (standard out-of-the-box react_on_rails):
const webpack = require('webpack');
const { resolve } = require('path');
const ManifestPlugin = require('webpack-manifest-plugin');
const webpackConfigLoader = require('react-on-rails/webpackConfigLoader');
const configPath = resolve('..', 'config');
const { devBuild, manifest, webpackOutputPath, webpackPublicOutputDir } =
webpackConfigLoader(configPath);
const config = {
context: resolve(__dirname),
entry: {
'webpack-bundle': [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/App/startup/registration',
],
},
output: {
// Name comes from the entry section.
filename: '[name]-[hash].js',
// Leading slash is necessary
publicPath: `/${webpackPublicOutputDir}`,
path: webpackOutputPath,
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false,
}),
new ManifestPlugin({ fileName: manifest, writeToFileEmit: true }),
],
module: {
rules: [
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
},
},
},
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: 'css-loader',
exclude: /node_modules/,
},
],
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
I am very new in webpack, and not sure how to I can add loaders to make it work, how can I apply the DateTime.css file that I have to be applied to react-datetime?
EDIT: added css-loader (also updated the webpack above). It is no longer complaining that I don't have the correct loader, but the CSS does not work.
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: 'css-loader',
exclude: /node_modules/,
},
],
There are 2 conceptually different ways to approach this.
1. Using CSS modules.
This way your CSS will end up bundled with your JS and as soon as webpack loads that JS module/bundle it will automatically append CSS style element into the head.
In my project I have this rule to do exactly that (note that we use both css-loader and style-loader):
{
test: /\.css$/,
use: ['style-loader', {
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}]
}
More on css-loader modules at this link.
2. Using ExtractTextPlugin. This way all your CSS will be extracted into a separate file. The configuration requires 2 things: a plugin and loaders configuration created by the plugin:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Add this to your webpack plugins array
new ExtractTextPlugin('styles.css')
And add this to your rules:
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
}
This will create one single styles.css file and put all CSS you import from JS into that file.

Resources