i want to add custom environment variables when using react-boilerplate.
In my DEV environment i will point the API to my localhost backend, but in PROD environment i will point it to the PROD backend.
I have tried using dotenv-webpack and react-scripts but still won't work.
for the dotenv-webpack i have add the plugins code below dllPlugin.
dllPlugin: {
...
},
plugins: [
new Dotenv({
path: './.env', // Path to .env file (this is the default)
systemvars: true,
safe: true // load .env.example (defaults to "false" which does not use dotenv-safe)
})
]
...
anyone have succeed applying this feature ? please throw some enlightment..
I have successfully implement the dotenv-webpack to the react-boilerplate. Before I misplaced the config at /config.js. Now i put in webpack/webpack.base.babel.js.
Related
We have a Laravel 8 application with Laravel Mix 6.0.49 and a React frontend. The application runs inside a docker container in production and development. Up until now, the frontend was compiled outside the docker container for some reason, but since we are moving to a fully dockerized environment, we are required to call the frontend scripts from inside the container. This all works fine, except for an environment variable we are setting in package.json, which allows us to pass the version of the app as a mix variable. Here is the current setup:
// package.json
"version": "0.1.1",
"scripts": {
...
"watch": "cross-env APP_VERSION=$(node -pe 'require(\"./package.json\").version') mix watch",
...
// .env
...
MIX_APP_VERSION="${APP_VERSION}"
...
// MyComponent.jsx
...
<div>version {process.env.MIX_APP_VERSION}</div>
...
The environment variable worked fine when the watch script was called outside the docker container.
Has anyone any idea of why it suddenly does not work anymore? I'm open to other ways of approaching this too.
I fixed this issue in the end by removing the variable related stuff from package.json including the cross-env dependency and setting the environment variable through the webpack config instead (webpack.mix.js)
...
.webpackConfig({
plugins: [
new webpack.DefinePlugin({
'process.env.APP_VERSION': JSON.stringify(
process.env.npm_package_version,
),
}),
],
})
I'm encountering the following error when attempting to open a project I forked via GitHub.
success open and validate gatsby-configs - 0.492s
ERROR #11331 PLUGIN
Invalid plugin options for "gatsby-source-contentful":
- "accessToken" is required
not finished load plugins - 6.220s
I've made several edits but am unable to work on the project as I'm unable to open it at the moment. I do have a contentful account, but am fairly new to Gatsby and am unaware of how to set a new value for the accessToken.
Would I need to do this via process.env, or am I missing the process entirely?
Thank you, any help is appreciated.
Would I need to do this via process.env, or am I missing the process
entirely?
Absolutely, you need to provide to Gatsby and Contentful your access tokens. Gatsby, by default, takes the .env.development and .env.production when running gatsby develop and gatsby build respectively, so you will need to add the credentials to the environment files.
First of all, add the following snippet in your gatsby-node.js, above the module exportation:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
This will tell Gatsby which file needs to be taken in each running command.
The next step is to fill the environment files, in both of them add:
CONTENTFUL_ACCESS_TOKEN=123456
CONTENTFUL_SPACE_ID=78910
So, finally your gatsby-config.js should look like:
// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
],
}
i am new to webpack, i have configured webpack to a working condition where my index.html file and budle.js file comes to /dist folder. iam aware that i can build css files too but for now i want to build js and run the app. please check the attached images for better understanding of the directory structure and the webpack build configuration.
My doubt is that if i run app from dist folder i would lose all the path of angular templates and image paths etc. how can i overcome this situation? any help is appreciated.
First of all, you need to know that the goal is to have a fully runnable stand alone application inside ./dist/ after build. All sourcefiles which are needed to run your application should be placed there. In that way you will be able to distribute your application by copy/upload/or-what-ever based on your ./dist/ directory. All other directories in your project are just for development. Those will be not a part of your distribution package.
Wrong approach: Trying to change the include path's in your application.
You need to copy or concat your sourcefiles (static files) into your distribution folder. I realy don't know why your views/templates are not stored in ./app/assets/ and not in ./app/views/ because ./app/views/ should be the correct path to store your views. Well, you need to copy your static sourcefiles. For example: You could use copy-webpack-plugin.
Your webpack config could look like this in the end:
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
module.exports = {
context: path.join(__dirname, 'app'),
devServer: {
// This is required for older versions of webpack-dev-server
// if you use absolute 'to' paths. The path should be an
// absolute path to your build destination.
outputPath: path.join(__dirname, 'dist')
},
plugins: [
new CopyWebpackPlugin([
{
from: 'assets/**/*',
to: 'assets/'
},
{
from: 'views/**/*',
to: 'views/'
},
], {
ignore: [
],
// By default, we only copy modified files during
// a watch or webpack-dev-server build. Setting this
// to `true` copies all files.
copyUnmodified: true
})
]
};
I know that console.log() will affect react native's pref under release mode, this is stated very clear in the docs, but what about console.debug() and console.warn()?
Otherwise what's the best way to print debug message and not having to take all of them out every time we go into release? Since we will need these message in dev mode again.
If you check the documentation, there are some instructions on how to use the babel plugin to automatically remove all the console.* calls in the release builds.
According to it [1], you just need to install the plugin:
1)
npm i babel-plugin-transform-remove-console --save
2) Add this in your .babelrc file:
{
"env": {
"production": {
"plugins": ["transform-remove-console"]
}
}
}
1 - https://facebook.github.io/react-native/docs/performance.html#using-console-log-statements
There are webpack plugins that are designed to remove specific types of console statements, depending on how you configure them, so that you can, for example, remove only console.debug statements but the last time I tried, I didn't have much luck.
If you are building a React JS app with a recent version of React, for example 15.x, that was created with create-react-app and you eject it with npm run eject, you'll have two separate webpack configurations. You can modify the production configuration (/config/webpack.config.prod.js) and remove all console statement from your production build by modifying the existing UglifyJsPlugin configuration in the plugins section so that it looks something like this:
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Drop console statements
drop_console: true, // <--- ADD THIS
},
output: {
comments: false,
},
sourceMap: true,
}),
That's all you should need to do... but again, this will remove all console statements, not just console.debug
Started using ReactJS's prop validation feature, which as the docs say only works in 'development mode' for performance reasons.
React seems to be validating the properties of a particular component I've annotated, but I don't remember explicitly turning on 'development mode'.
I tried searching for how to trigger/toggle development mode, but haven't had any luck.
The other answer assumes you are using external pre-built files from react, and while correct that is not how most folks are going to or should consume React as a package. Moreover, at this point most every React library and package also relies on the same convention to toggle dev time helpers off during production. Just using the minified react will leave all those potential optimizations on the table as well.
Ultimately the magic comes down to React embedding references to process.env.NODE_ENV throughout the codebase; these act like a feature toggle.
if (process.env.NODE_ENV !== "production")
// do propType checks
The above is the most common pattern, and other libraries follow it as well. So to "disable" these checks we need to toggle NODE_ENV to "production"
The proper way to disable "dev mode" is through your bundler of choice.
webpack
Use the DefinePlugin in your webpack config like so:
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("production")
})
Browserify
Use the Envify transform and run your browserify build step with NODE_ENV=production ("set NODE_ENV=production" on Windows)
Result
This will produce output bundles that has all instances of process.env.NODE_ENV replaced with the string literal: "production"
Bonus
When minifying the transformed code you can take advantage of "Dead Code Elimination". DCE is when the minifier is smart enough to realize that: "production" !== "production" is always false and so will just remove any code in the if block saving you bytes.
Yeah, it's not really well documented, but on the ReactJS download page it talks about development and production modes:
We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
Basically, the unminified version of React is "development" mode, and the minified version of React is "production" mode.
To be in "production" mode, just include the minified version react-0.9.0.min.js
I posted this elsewhere but, frankly, here would be a better place.
Assuming you install React 15.0.1 with npm, import react from 'react' or react = require('react') will run ./mode_modules/react/lib/React.js which is React's raw source.
The React docs suggest you use ./mode_modules/react/dist/react.js for development and react.min.js for production.
Should you minify /lib/React.js or /dist/react.js for production, React will display a warning message that you've minified non-production code:
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See fb.me/react-minification for more details.
react-dom, redux, react-redux behave similarly. Redux displays a warning message. I believe react-dom does too.
So you are clearly encouraged to use the production version from /dist.
However if you minify the /dist versions, webpack's UglifyJsPlugin will complain.
WARNING in ../~/react/dist/react.js
Critical dependencies:
4:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ../~/react/dist/react.js 4:478-4851
You cannot avoid this message because UglifyJsPlugin can only exclude webpack chunks, not individual files.
I use the both the development and production /dist versions myself.
Webpack has less work to do and finishes a bit sooner. (YRMV)
React docs say /dist/react.min.js is optimised for production. I've read no proof that 'process.env': { NODE_ENV: JSON.stringify(IS_PRODUCTION ? 'production' : 'development') } plus uglify does as good a job as '/dist/react.min.js`. I've read no proof you get the same resulting code.
I get 1 warning message from uglify rather than 3 from the react/redux ecosystem.
You can have webpack use the /dist versions with:
resolve: {
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist',
(IS_PRODUCTION ? 'react.min.js' : 'react.js')),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist',
(IS_PRODUCTION ? 'react-dom.min.js' : 'react-dom.js')),
'redux$': path.join(__dirname, 'node_modules', 'redux','dist',
(IS_PRODUCTION ? 'redux.min.js' : 'redux.js')),
'react-redux$': path.join(__dirname, 'node_modules', 'react-redux','dist',
(IS_PRODUCTION ? 'react-redux.min.js' : 'react-redux.js'))
}
}
For webpack based build, I used to setup separate webpack.config.js for DEV and PROD. For Prod, resolve the alias as below
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist','react.min.js'),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist','react-dom.min.js')
}
You can find the working one from here
If you're working from something like this ReactJS.NET / Webpack tutorial, you can't use process.env to switch React development mode on/off as far as I can tell. This sample links to react.js directly (see Index.cshtml), so you just have to pick .min.js or the non-minified variant by changing the URL.
I'm not sure why that is the case, because the sample's webpack.config.js has a comment that seems to imply the externals: { react: 'React' } would do the job, but then goes ahead and includes react directly into the page.
I use a manual build process that runs through Webpack, so it was a two-step process for me:
Set the environment variable from package.json using the cross-env package:
"scripts": {
"build-dev": "cross-env NODE_ENV=development webpack --config webpack.config.js",
"build-prod": "cross-env NODE_ENV=production webpack --config webpack.config.js"
}
Change the webpack.config.js file to use the environment variable (which is passed-on to React to determine if we are in development or production mode), and disable minimizing the produced bundle if we are in development mode so we can see the actual names of our components. We need to use webpack's optimization property in our webpack.config.js file for this:
optimization: {
nodeEnv: process.env.NODE_ENV,
minimize: process.env.NODE_ENV === 'production'
}
webpack v4.41.5, React v16.9.19, cross-env v7.0.0, node v10.16.14
For only Webpack v4 users:
Specifying mode: production and mode: development in your Webpack config will define process.env.NODE_ENV using the DefinePlugin by default. No additional code necessary!
webpack.prod.js (taken from docs)
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
});
And in our JS:
console.log(process.env.NODE_ENV) // --> 'development' or 'production'
Webpack Docs: https://webpack.js.org/guides/production/#specify-the-mode