Commonjs : during the build, How to change the extension of file - reactjs

I am able to transpile scss file to css file but the only importing is not working during the build. since *.js its importing a .scss file. I tried replacing .scss with .css during the build.
js still has references to scss files which do not exist in the dist folder as all scss there is distributes as normal css
error :
ERROR in ./src/Checkbox/Checkbox.js
Module not found: Error: Can't resolve './Checkbox.css' in '/src/Checkbox'
# ./src/Checkbox/Checkbox.js 36:0-22
# ./src/index.js**
src/checkbox.js
'use strict';
import {Checkbox} from 'semantic-ui-react';
import * as React from 'react';
import PropTypes from 'prop-types';
// Style
import './Checkbox.scss';
react code...
dist/checkbox.js transpiled JS file (looks like )
var _propTypes2 = _interopRequireDefault(_propTypes);
require('./Checkbox.scss');
**I am expecting require('./Checkbox.css');**
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
and so on ...
*.js its importing a .scss file. I tried replacing .scss with .css during the build
my webpack.config.js
const webpack = require('webpack')
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractLESS_checkbox = new ExtractTextPlugin({
filename: 'component/Checkbox.css',
allChunks: true
});
const config = {
entry : {
index:'./src/index.js'
},
output : {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
pathinfo: true
},
devtool: 'source-map',
module: {
rules: [{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
//enforce: 'pre',
exclude: /node_modules/,
}, {
test: /\.scss$/,
enforce: 'pre',
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
['css-loader', 'resolve-url-loader', 'sass-loader']})
]
},
plugins: [
extractLESS_checkbox
],
externals: {
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
};
module.exports = config;
my package.json
"name": "name",
"version": "0.1",
"description": "Elements",
"author": "dg",
"license": "ISC",
"jsnext:main": "dist/es/index.js",
"main": "dist/commonjs/index.js",
"module": "dist/es/index.js",
"scripts": {
"build": "npm run build:commonjs && npm run build:es",
so on ....
}
"dependencies" : { ...}
"devDependencies" : {... }
Am I doing something wrong, Please suggest me

Use Extract text plugin
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
},
}, {
loader: 'sass-loader',
options: {
sourceMap: true
},
}, {
loader: 'import-glob-loader',
},
]
})
Should look something like this

Related

Problems with images in react application

When using images in react, there is either a problem with typescript, or the image breaks on the site.
To solve the problem, I tried:
Add url-loader and file-loader to the webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BUILD_PATH = path.resolve(__dirname, './build');
const SRC_PATH = path.resolve(__dirname, './src/');
const PUBLIC_PATH = path.resolve(__dirname, './public')
module.exports = {
entry: SRC_PATH + '/index.tsx',
output: {
path: BUILD_PATH,
filename: 'bundle.js',
},
mode: process.env.NODE_ENV || 'development',
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
extensions: [ '.tsx', '.ts', '.js' ],
},
devServer: {
static: PUBLIC_PATH,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: 'ts-loader'
},
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.module.css$/,
use: [
{
loader: "css-loader",
options: {
modules: true,
},
},
],
},
{
test: /\.(jpg|png|svg)$/,
loader: 'url-loader',
options: {
limit: 8192,
},
},
{
test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
use: ['file-loader']
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
}),
],
};
Import images as components
import React from 'react';
import logo from './header-logo.svg';
import styles from './Header.module.scss';
export const Header = () => {
return <header className={styles.header}>
<img src={logo} />
</header>
};
Create the images.d.ts file in the src/types directory
declare module "*.svg" {
const content: any;
export default content;
}
And I even tried svgr..
But nothing helped. If I delete the images.d.ts file, typescript cannot detect the module when importing. When using images.d.ts, vscode does not show errors, but the picture is not displayed in the browser, and instead of the normal path, something strange data:image/svg+xml;base64,ZXhwb3J0IGRlZmF1bHQgX193ZWJwYWNrX3B1YmxpY19wYXRoX18gKyAiZWMzYzM1Nzg3YTljZTMyMzE4M2NmMzM2Y2EzMDBkOTkuc3ZnIjs=
And just in case, I attach tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"outDir": "./build/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"plugins": [
{
"name": "typescript-plugin-css-modules"
},
],
},
}
I'm new to react so please don't judge strictly for stupid mistakes. I would appreciate any advice!
You can use svg-url-loader npm module. in webpack.config,js
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
in your component
// pass a correct path
import logo from './header-logo.svg';
<img src={logo} alt="" />
After some thought, I came to the conclusion that perhaps the problem occurred due to a loaders conflict. Leaving only the file-loader and deleting the url-loader, I was able to solve the problem. I hope my solution can help someone in the future.
My files now look like this:
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SRC_PATH = path.resolve(__dirname, './src');
const BUILD_PATH = path.resolve(__dirname, './build');
const PUBLIC_PATH = path.resolve(__dirname, './public')
module.exports = {
entry: SRC_PATH + '/index.tsx',
output: {
path: BUILD_PATH,
filename: 'bundle.js',
},
mode: process.env.NODE_ENV || 'development',
resolve: {
modules: [SRC_PATH, 'node_modules'],
extensions: [ '.tsx', '.ts', '.js' ],
},
devServer: {
static: PUBLIC_PATH,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: 'ts-loader'
},
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.module.css$/,
use: [
{
loader: "css-loader",
options: {
modules: true,
},
},
],
},
{
test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
use: ['file-loader']
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: PUBLIC_PATH + '/index.html',
}),
],
};
A imges.d.ts file for type resolution for typescript
declare module "*.jpg";
declare module "*.png";
declare module "*.svg";

Autodesk React Forge problem with forge-dataviz-iot-react-components in a empty project

If you install the official npm package, it works.
But according to the official documentation and simply including import { Viewer } from "forge-dataviz-iot-react-components" (like in this example) in a empty new react project (using npx create-react-app) you will get this error:
./node_modules/forge-dataviz-iot-react-components/client/components/BasicTree.jsx 107:16
Module parse failed: Unexpected token (107:16)
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
| if (node.children.length > 0) {
| return (
> <TreeItem
| id={`tree-node-${node.id}`}
| key={node.id}
Which loader do I need to add on webpack to avoid this error?
it is not possible to include the package https://www.npmjs.com/package/forge-dataviz-iot-react-components inside a react project made with npx create-react-app (hoping Autodesk is going to fix this problem soon).
You need to edit /node_modules/react-scripts/config/webpack.config.js in 2 parts:
one line about PIXI
...
alias: {
'PIXI': "pixi.js/",
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
...
and another part about /forge-dataviz-iot-react-component
...
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
{
test: /forge-dataviz-iot-react-component.*.jsx?$/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
presets: ["#babel/react", ["#babel/env", { "targets": "defaults" }]],
plugins: ["#babel/plugin-transform-spread"]
}
},
],
exclude: path.resolve(__dirname, "node_modules", "forge-dataviz-iot-react-components", "node_modules"),
},
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
mimetype: 'image/avif',
name: 'static/media/[name].[hash:8].[ext]',
},
},
...
after that on /node_modules/forge-dataviz-iot-react-components/client/components/Viewer.jsx you will get errors about undefined Autodesk variable easily fixable changing Autodesk with window.Autodesk.
Although you will not see any other errors, the package will not work.
I recently tried this package and I got the same problem.
So I created a React project from scratch without CRA and followed the webpack.config.js of this repo : Forge Dataviz IOT Reference App
Here's my webpack.config.js file :
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
PIXI: path.resolve(__dirname, "node_modules/pixi.js/"),
},
},
devServer: {
port: process.env.PORT || 3000
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{ loader: "babel-loader" }
]
},
{
test: /forge-dataviz-iot-react-component.*.jsx?$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/react", ["#babel/env", { "targets": "defaults" }]],
plugins: ["#babel/plugin-transform-spread"]
}
},
],
exclude: path.resolve(__dirname, "node_modules", "forge-dataviz-iot-react-components", "node_modules"),
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.svg$/i,
use: {
loader: "svg-url-loader",
options: {
// make loader to behave like url-loader, for all svg files
encoding: "base64",
},
},
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
],
};
Update :
If you want to use CRA, you can customise your webpack config using Customize-CRA and create a config-overrides.js like this :
/* config-overrides.js */
const path = require("path");
const {
override,
addExternalBabelPlugins,
babelInclude,
babelExclude,
addWebpackAlias
} = require("customize-cra");
module.exports = override(
babelInclude([
path.resolve("src"), // make sure you link your own source
path.resolve("node_modules")
]),
babelExclude([path.resolve("node_modules/forge-dataviz-iot-react-components/node_modules")]),
addWebpackAlias({
['PIXI']: path.resolve(__dirname, 'node_modules/pixi.js/')
})
);
I managed to make this work on a fresh CreateReactApp project, so you should be able to make it working on your project.

toastr not showing when imported in a jsx file

I have a react app that uses webpack to bundle JS and CSS into 1 file and output it into a destination folder. I've recently added toastr to 1 of my jsx file:
import toastr from "toastr";
import "toastr/build/toastr.min.css"
Running the app and viewing the source, i've verified in the browser (viewing the source files) that toastr.min.js is included in the JS bundle and toastr.min.css is included in the CSS bundle. However, the toastr notification doesn't show. There is no error and a scrollbar appears in the right-side for a few seconds so I suspected the toastr code is working, just that the CSS is not properly styling for some reason.
I removed this line:
import "toastr/build/toastr.min.css"
and then directly added this to html
<link rel="stylesheet" type="text/css" href="~/css/toastr.min.css" />
and now it works. But I want to make it work where toastr.min.css is included in the bundle. Is there anything I'm missing?
webpack config
const path = require("path");
const webpack = require("webpack");
const miniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
home: "./Scripts/Components/Home/main.js",
login: "./Scripts/Components/Login/main.js",
vendor: [
"jquery",
"react",
"react-dom",
"react-router-dom",
"react-css-modules",
]
},
mode: "development",
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
chunks: "all",
name: "vendor",
test: "vendor",
enforce: true
}
}
}
},
output: {
publicPath: "/js/",
path: path.join(__dirname, "/wwwroot/js/"),
filename: "[name].bundle.js"
},
devtool: "source-map",
plugins: [
new miniCssExtractPlugin({
filename: "../css/[name].css"
}),
],
module: {
rules: [{
test: /\.jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}, {
test: /\.css$/,
use: [{
loader: miniCssExtractPlugin.loader,
}, {
loader: "css-loader",
query: {
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
}
}]
}]
}
};

Webpack 4 configuration for react-toolbox

I try to upgrade my app from webpack 2 to webpack 4.16.5.
Because I want not again end up in a hard to understand some hundreds line config, I start with a minimal config. This is my current:
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const context = path.resolve(__dirname, "app");
module.exports = {
entry: {
home: "./index.js"
},
context,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "postcss-loader"
},
{
loader: "sass-loader"
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
resolve: {
extensions: [".js", ".jsx", ".css", "json"],
modules: [path.resolve(__dirname, "node_modules"), context]
}
};
But I run in problems importing the CSS files from react-toolbox i.e.:
import Dialog from 'react-toolbox/lib/dialog';
in a js file and also
#import "react-toolbox/lib/button/theme.css";
causes errors like this:
ERROR in ../node_modules/react-toolbox/lib/switch/theme.css (../node_modules/css-loader!../node_modules/postcss-loader/src!../node_modules/sass-loader/lib/loader.js!../node_modules/react-toolbox/lib/switch/theme.css)
Module build failed (from ../node_modules/css-loader/index.js):
Error: composition is only allowed when the selector is single: local class name not in ".disabled", ".disabled" is weird
Does anyone have a working application with wbpack4 and react-toolbox? Also, any hints on what may cause these errors are welcome!
I'm learning react.js with the js stack from scratch tutorial and try to using react-toolbox components.
Finnaly, i have a working demo with webpack 4 and the react-toolbox, it's based on the react-toolbox-example.
This is my settings:
add css-modules related packages
$ npm install postcss postcss-cssnext postcss-import postcss-loader css-loader style-loader
add a postcss.config.js
module.exports = {
plugins: {
'postcss-import': {
root: __dirname,
},
'postcss-cssnext': {}
},
};
add a webpack rule
...
{ test: /\.css$/, use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]--[local]--[hash:base64:8]'
}
},
'postcss-loader'
]},
...
add cmrh.conf.js - Using the css-modules-require-hook for SSR(Optional)
module.exports = {
generateScopedName: '[name]--[local]--[hash:base64:8]'
}
You can see all the settings in here, hope it will work for you.

electron with react and webpack

I am trying to run a simple electron app with webpack and react.
So I set my webpack with target: "electron"
const webpack = require('webpack');
const path = require('path');
const SassLintPlugin = require('sasslint-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css',
disable: process.env.NODE_ENV === 'development',
});
module.exports = {
target: 'electron',
context: path.resolve(__dirname),
entry: {
app: './assets/js/components/index',
main: './main',
},
output: {
publicPath: '/dist/',
path: path.resolve('./dist/'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'eslint-loader',
include: path.resolve(__dirname, './assets/js/'),
exclude: /node_modules/,
enforce: 'pre',
},
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './assets/js/'),
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.scss$/,
include: path.resolve(__dirname, './assets/scss/'),
loader: extractSass.extract({
use: [
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
],
// use style-loader in development
fallback: 'style-loader',
}),
exclude: /node_modules/,
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file?name=public/fonts/[name].[ext]',
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [path.resolve(__dirname, 'node_modules')],
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['main'],
}),
new SassLintPlugin({
configFile: '.sass-lint.yml',
context: [path.resolve(__dirname, './assets/scss/')],
ignoreFiles: [],
ignorePlugins: [],
glob: '**/*.s?(a|c)ss',
quiet: false,
failOnWarning: false,
failOnError: true,
testing: false,
}),
extractSass,
new HtmlWebpackPlugin({
title: 'Calendar Component',
template: 'assets/index-template.html',
minify: {
collapseWhitespace: process.env.NODE_ENV === 'production',
},
}),
],
};
My bundles are created correctly into index.html, app.js and main.js and ./dist folder.
But I got an error: Unable to find Electron at my_path_project/dist
My scripts at package.json are:
"main": "./dist/main.js",
"scripts": {
"start": "electron ./dist/",
"dev": "NODE_ENV=development webpack"
},
Can anyone help me?
Thanks in advance.
Probably because there is no one. You are install electron to your node modules, you are referring to that in modules: [path.resolve(__dirname, 'node_modules')].
Simply change your start command to:
"main": "dist/main.js",
"scripts": {
"start": "electron ."
},
The solution from #Anatoly helped me to appear the electron windows, but I couldn't run react over electron.
So I found this tutorial that worked to run react over electron:
https://medium.freecodecamp.com/building-an-electron-application-with-create-react-app-97945861647c
I hope this will help ;)

Resources