How to set root directory for webpack - reactjs

I am configuring webpack for react storybook and I am having issues with the import statements paths. When I normally run my app, I have a path like this:
import { constructURLName } from "src/shared/utilities/stringManipulation";
I am using the reactQL boilerplate and it is configured so that it will return the proper module based on the src folder. How can I replicate that in storybook? Storybook currently tries to look for that stringManipulation file here:
/Users/me/development/reactQL/node_modules/src/shared/utilities/stringManipulation
So it needs to go up one directory based on my layout:
node_modules
src
pages
...
shared
utilities
stringManipulation
This is what my rule looks like for js/jsx files:
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
query: {
babelrc: false,
presets: [
["env", { modules: false, exclude: ["transform-regenerator"] }],
"react"
],
plugins: [
"transform-object-rest-spread",
"syntax-dynamic-import",
"transform-regenerator",
"transform-class-properties",
"transform-decorators-legacy"
]
}
}
]
},
How can I properly set the src directory? Thanks!

You can use resolve.modules.
const path = require('path');
const config = {
...
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, './'),
]
}

Related

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.

How to make React to ignore some folder files updates and don't recompile?

I've got problem - on some requests backend creates static html files in frontend subfolder which causes React to recompile and reload page. This is bad for me.
If simplify, I've got following project directory structure:
backend/
...
frontend/
node_modules/
package.json
package-lock.json
public/
statements/
...
src/
webpack.config.js
...
...
I want React to ignore public/statements folder updates.
How could I make it?
Found that maybe I should configure Webpack exlude rule, but I failed to do it.
UPD1: Here is my webpack.config.js:
module.exports = {
module: {
rules: [
{
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /public/
}
]
}
};
UPD2: Tried also this one, same trouble:
const path = require('path');
module.exports = {
devServer: {
watchOptions: {
ignored: [
path.resolve(__dirname, 'public', 'statements'),
]
}
}
};
in the webpack.config.js file set the rules property array and set exclude folder
like this
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /public/statements/
}
For HMR reloading?
devServer: {
watchOptions: {
ignored: [
path.resolve(__dirname, 'public', 'statements'),
]
}
}

Babel + Webpack doesn't transpile ES6 [duplicate]

This question already has answers here:
How to use arrow functions (public class fields) as class methods?
(4 answers)
Closed 5 years ago.
I just set up the environment for a webapp using react.
setInitialStates = () => {
this.state = {showAuthorModal: false};
};
NOTE: This is the correct syntax!
This happens when I tried to run webpack --config webpack.config.js
This is my webpack.config.js.
const path = require('path');
module.exports = {
entry: {
component: [
'./public/javascripts/Rendering.jsx',
'./public/javascripts/CentreQuote.jsx',
'./public/javascripts/AuthorModal.jsx',
'./public/javascripts/LeftNav.jsx'
]
},
output: {
path: path.resolve('public/javascripts'),
filename: 'index_bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
]
}
}
Then I have .babelrc,
{
"presets":[
"es2015", "react"
],
"plugins": ["transform-es2015-arrow-functions"]
}
I think I'm missing some wiring step that links babelrc to the loader config?
replace the "module" in webpack with the following:
module: {
rules: [{
test: /\.jsx?$/,
loader: "babel-loader",
options: {
cacheDirectory: true, //false for production
babelrc: false,
presets: ["es2015", "react"],
plugins: ["transform-es2015-arrow-functions"]
}
}]
}
I did 2 things:
unified the js/jsx loader in one regex test
stopped using the babelrc to be able to specify the configs inside webpack.
it should work! give it a try
The main issue with the code you provided is that you have "loaders" but it should be "rules"

Using multiple Webpack loaders to transform SVGs into React components

I am trying to combine several Webpack loaders together to load my SVG assets, transform them for inline usage and finally to convert the result into an actual React component that can be used in the application.
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src'),
use: {
loader: 'babel-loader',
options: {
presets: [
['env', {
browsers: supportedBrowsers,
modules: false
}]
]
}
}
},
{
test: /\.svg$/,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'svg-inline-loader',
options: {
removeTags: true
}
},
{
loader: 'svg-react-loader'
}
]
}
]
}
}
If svg-react-loader is used on it's own the loader works as expected, however a lot of SVG assets have unneeded elements and attributes I would like to strip out using svg-inline-loader.
When the configuration is used as above the result will be loaded as text instead of executable JavaScript.
I am using the following loaders in my attempt to accomplish this:
https://github.com/webpack-contrib/svg-inline-loader
https://github.com/jhamlet/svg-react-loader
Would it be ok to use other loaders? You can combine svgo-loader with svg-inline-loader and use all the possible options provided by svgo.
If so just do npm i -D svgo-loader
And change your webpack config to this:
{
test: /\.svg$/,
use: [
'svg-react-loader',
{
loader: 'svgo-loader',
options: {
plugins: [
{cleanupAttrs: true}
]
}
}
],
exclude: /node_modules/
}

"composes" not working with babel-plugin-react-css-modules

I'm trying to use css modules in my React project. I am able to do things like:
import styles from './demo.css'
const Demo = () => <div styleName="demo">Hello</div>
And my styles are pulled from the CSS and prefixed successfully. However, when I try to use the "composes" function of CSS modules, it seems like it is completely ignored. I'm not even importing from other files - just trying to compose local classes. However, when I clone the demo project (https://github.com/gajus/babel-plugin-react-css-modules/tree/master/demo) and add a "composes" in the CSS, it works. I don't see what the difference is between my code and that in the demo...
My webpack loaders are:
loaders: [
{
test: /\.jsx?$/,
loader: 'babel?cacheDirectory',
include: PATHS.src
},
{
test: /\.css$/,
loaders: [
'style',
'css?importLoader=1&modules&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
],
include: PATHS.src,
}
]
This is my .babelrc:
{
presets: [
"es2015",
"react",
],
plugins: [
[
"react-css-modules",
{
generateScopedName: "[path]___[name]__[local]___[hash:base64:5]"
}
],
"transform-object-rest-spread",
],
env: {
development: {
presets: [
"react-hmre"
]
}
}
}
Having the same issue here. The workaround I found is by using vars instead composes.
/* colors.css */
:root {
--color: #4A90E2
}
/* button.css */
#import 'colors.css';
.button {
color: var(--blue);
}
I had this problem, and found that it was solved by adding cacheDirectory: false
For example webpack.config.js:
...
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader',
query: 'cacheDirectory=false',
},
...

Resources