How does webpack v4 handle devDependencies in production mode? - reactjs

I'm wondering how does webpack handle devDependencies when in production mode:
App.js
import { hot } from 'react-hot-loader';
function App() {
// App code
}
export default process.env.NODE_ENV === 'development' ? hot(module)(App) : App;
I can successfully use a ternary into the export statement. But I can't do that and neither set a condition in the import statement.
QUESTION
What is the proper way to handle this (the import of a devDependency)?
Will webpack add devDependencies to the bundle if no condition is placed at the import?
EDIT:
Just found out that webpack does add devDependencies to the bundle:
This was generated with webpack mode set to production:

Here's how I solved it with ignorePlugin
App.js
import { hot } from 'react-hot-loader';
function App() {
// App code
}
export default process.env.NODE_ENV === 'development' ? hot(module)(App) : App;
webpack.prod.js (webpack production config file)
module.exports = merge(common, {
mode: 'production',
plugins:[
new webpack.IgnorePlugin(/react-hot-loader/), // <------ WILL IGNORE THE react-hot-loader
new webpack.HashedModuleIdsPlugin(),
new BundleAnalyzerPlugin()
],
This way react-hot-loader is ignored in production mode.
In development I use another config file for webpack, which doesn't use the ignorePlugin.

You can have two new files for app, app.dev.js and app.prod.js while in app you just switch the require based on env.
// App.js
let App;
if (process.env.NODE_ENV === 'development') {
App = require('./app.dev.js')
} else {
App = require('./app.prod.js')
}
export default App
EDIT:
It's essential that require is used instead of import as only require can be used dynamically like this.

Related

How to import SVG in ReactJS with craco?

I'm struggling to import SVG's when I'm using craco in my react app.
It's suggested to use #svgr/webpack but I'm not sure how to put it into my craco.config.js
My current setup as per this (I prob shouldn't follow someone's config that doesn't work and expect it to work tho) that does not work:
// craco.config.js
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
The craco.config.js webpack documentation is here but it's so confusing to me without concrete examples.
Also to note:
Writing import {ReactComponent as mySvg} from "./mySvg.svg" doesn't work because it doesn't recognize it as a ReactComponent.
If I try importing directly via import mySvg from "./mySvg.svg" Typescript doesn't recognize the file.
What I'm currently doing is putting the svg into a React component and using that but it's a nightmare doing that every time. I also put this in #types/custom.d.ts, but it still doesn't work when put into <img src={mySvg} />
// #types/custom.d.ts
declare module "*.svg" {
const content: any;
export default content;
}
import {reactComponent as GoogleLogo} from "../assets/image/googlelogo.svg;
GoogleLogo is component and reactComponent is a required magic string
i find the fix your problem in Adding svgr to create-react-app via craco

Error on deployment: Argument of type 'MiniCssExtractPlugin' is not assignable to parameter of type 'Plugin'

I want to deploy a Typescript / React project. I have already done the following steps:
Create branch for deployment
Install gh-pages to run deployed application
added deploy command as script in the package json
After running the yarn deploy command in the git console the following error is shown:
ERROR in C:\Users\Jorrit-Business\School\my-project\webpack\config.ts
[tsl] ERROR in C:\Users\Jorrit-Business\School\my-project\webpack\config.ts(29,5)
TS2345: Argument of type 'MiniCssExtractPlugin' is not assignable to parameter of type 'Plugin'.
The code in webpack\config.ts looks like this:
import bgImage from "postcss-bgimage";
import HtmlWebpackPlugin from "html-webpack-plugin";
import * as webpack from "webpack";
import * as path from "path";
const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;
import autoprefixer from "autoprefixer";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import OptimizeCSSAssetsPlugin from "optimize-css-assets-webpack-plugin";
import TerserPlugin from "terser-webpack-plugin";
import ReactRefreshWebpackPlugin from "#pmmmwh/react-refresh-webpack-plugin";
import svgoConfig from "#triply/utils/lib/svgo";
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
import { compact } from "lodash";
export const analyzeBundle = process.env["ANALYZE_BUNDLE"] === "true";
const plugins: webpack.Plugin[] = [
new webpack.DefinePlugin({
__DEVELOPMENT__: isDev,
}),
];
if (isDev) {
plugins.push(new ReactRefreshWebpackPlugin());
//ignore these, to avoid infinite loops while watching
plugins.push(new webpack.WatchIgnorePlugin([/\.js$/, /\.d\.ts$/]));
} else {
plugins.push(
new MiniCssExtractPlugin({
filename: "[name].min.css",
chunkFilename: "[id].css",
})
);
} ...
The code file itself shows no errors. Am I missing something here? Note: I have already tried to reinstall the MiniCssExtractPlugin (v0.9.0) dependency.
I know it's been a while since this unanswered thread has been opened, but if this is still a problem (or for anyone who may run into it):
The issue was solved for me by upgrading #types/mini-css-extract-plugin to version 1.2.1. Seems that for previous versions this was a known issue.

React-hot-loader: `hot` could not find the `name` of the the `module` you have provided

I'm using Webpack 4 to create a React project with hooks and I'm trying to get the changes to reload on page live using react-hot-loader following this tutorial.
But I when I try npm start I get following error on the browser:
Error: React-hot-loader: hot could not find the name of the the
module you have provided
This is my App.js contents:
import React from 'react';
import { hot } from 'react-hot-loader';
import Header from './Header';
function App() {
return (
<section className="main">
<Header />
</section>
);
}
export default hot(App);
Alternately I tried importing hot from react-hot-loader/root, but this way I get a different error:
Error: React-Hot-Loader: react-hot-loader/root is not supported on
your system. Please use import {hot} from "react-hot-loader" instead
How could I solve this issue?
You should be requiring it before react:
import { hot } from 'react-hot-loader/root';
import React from 'react';
The package documentation mentions this.
Well, looking at my webpack configs:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
],
devServer: {
contentBase: './dist',
hot: true,
},
I had used webpack.HotModuleReplacementPlugin() in plugins and hot: true in devServer which made the second error if I would use react-hot-loader/root.
So removing new webpack.HotModuleReplacementPlugin() from the webpack.config.js, solved my problem.
import { hot } from 'react-hot-loader';
export default hot(module)(App);
or
import { hot } from 'react-hot-loader/root';
export default hot(App);

Create-React-App: .env file doesn't parse correctly

My CRA project isn't parsing my environment variables. I see this in the docs:
By default you will have NODE_ENV defined for you, and any other
environment variables starting with REACT_APP_
And here is some code for testing:
// .env in the project root folder
REACT_APP_GOOGLE=google.com
REACT_APP_API_POST_URL=http://localhost:4000/api/
// App.js
import dotenv from 'dotenv';
componentDidMount() {
if (dotenv.error) {
console.log('dotenv.error', dotenv.error);
} else { console.log('dotenv.parsed', dotenv.parsed); // undefined
}
}
// App.js insider render()
<button
onClick={e => {
e.preventDefault();
console.log("process.env", process.env); //
// {NODE_ENV: "development", PUBLIC_URL: ""}
// NODE_ENV: "development"
// PUBLIC_URL: ""
console.log("process.env.NODE_ENV", process.env.NODE_ENV); // development
console.log("process.env.REACT_APP_GOOGLE", process.env.REACT_APP_GOOGLE); // undefined
}}
>log .env</button>
Anyone know why it's not parsing the env variables?
Here is your component:
import React, { Component } from 'react';
import './App.css';
const googleEnvVariable = process.env.REACT_APP_GOOGLE;
class App extends Component {
render() {
return <div className="App">{googleEnvVariable}</div>;
}
}
export default App;
And here is your .env
REACT_APP_GOOGLE=hereisyourenvvar
You should see hereisyourenvvar
EDIT: updated answer to display on the screen instead of the console.log...
From the code you gave, it seems like you forgot to call the config function (unless you didn't show it). If you want your .env to be implemented, you will have to do the following at the top level of your project :
import dotenv from 'dotenv';
// Load ENV vars
const dotEnvOptions = {
path: 'env/dev.env' //Example path relative to your project folder
}
dotenv.config(dotEnvOptions)
To figure out what is going wrong you may turn on logging to help debug why certain keys or values are not being set as you expect :
dotenv.config({ debug: true })
From there, if a path/variable isnt recognized, it will be printed int he console :
If you are not seeing anything, it either means that your path is wrong or that the code isn't executed

How to create a hello world application using isomorphic-webpack?

I want to create a simple application that outputs "Hello, World!" using isomorphic-webpack.
The most simple way is to use the createIsomorphicWebpack high-level abstraction.
First, you need to have have a basic webpack configuration.
webpack configuration does not need to define any special configuration for isomorphic-webpack, e.g. this will work:
import path from 'path';
import webpack from 'webpack';
const webpackConfiguration = {
context: __dirname,
entry: {
'app': [
path.resolve(__dirname, './app')
]
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].js'
},
module: {
loaders: []
}
};
Next, run createIsomorphicWebpack:
import {
createIsomorphicWebpack
} from 'isomorphic-webpack';
createIsomorphicWebpack(webpackConfiguration);
What this does is:
Creates a new webpack compiler.
Runs compiler in watch mode.
Overrides require to use compiled assets.
Therefore, now all you need is to require the entry script:
import {
createServer
} from 'http';
http
.createServer((request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end(request('./app'));
})
listen(8000);
The entry script must be environment aware, i.e. it must return for node.js process and it must use whatever client specific logic otherwise, e.g.
import React from 'react';
import ReactDOM from 'react-dom';
import style from './style.css';
const app = <div className={style.greetings}>Hello, World!</div>;
if (typeof process === 'undefined' || !process.release || process.release.name !== 'node') {
ReactDOM.render(app, document.getElementById('app'));
}
export default app;
Since this entry script is using css and react, you will need to add the missing loaders to your webpack configuration:
babel-loader and babel-react-preset
css-loader
style-loader

Resources