nuxt.config.js: load different config for development or production - config

How can I load for production and development different settings.
I want something like this for example:
nuxt.config.js
sentry: {
dsn: 'xxx',
config: {
disabled: !env.isDev
}
},
Unfortunately isDev is not usable at that stage.

Create 2 different config files:
nuxt.config.dev.js
nuxt.config.js
and in package.json in scripts section specify config file for dev version
with --config-file nuxt.config.dev.js:
"scripts": {
"dev": "cross-env NODE_ENV=development HOST=111.111.111.111 PORT=3001 nodemon --watch api --exec \"nuxt --config-file nuxt.config.dev.js --spa\"",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production HOST=111.111.111.111 PORT=3002 nuxt start --spa "
}

Thank you for the good input.
In the meantime a found an other solution which is working fine for my current use case.
nuxt.config.js
import stdEnv from 'std-env'
...
sentry: {
dsn: 'xxx',
config: {
disabled: !stdEnv.dev
}
},
...
I think this is a good and easy solution if you have only little difference to your production setup.
At the end I will probably use a mix of both.
EDIT:
importing 'std-env' in nuxt.config.js gave me some problems on production.
I use this peace of code at the moment without any issues:
(process.env.NODE_ENV === 'development')
That way you don't need to import anything!

Related

Different vue.config.js for npm run serve and npm run build

I'm overriding webpack config using vue.config.js:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: 'http://0.0.0.0:8080',
outputDir: './dist/',
chainWebpack: config => {
config.optimization
.splitChunks(false)
config
.plugin('BundleTracker')
.use(BundleTracker, [{ filename: './webpack-stats.json' }])
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://0.0.0.0:8080')
.host('0.0.0.0')
.port(8080)
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.headers({ "Access-Control-Allow-Origin": ["*"] })
}
};
The webpack-bundle-tracker plugin generates a file called webpack-stats.json:
{
"status": "done",
"publicPath": "http://0.0.0.0:8080/",
"chunks": {
"app": [
{
"name": "app.js",
"publicPath": "http://0.0.0.0:8080/app.js",
"path": "/Users/me/dev/vue-app/dist/app.js"
}
]
}
}
My problem is that depending on whether I am in development or in production, I want the path to the file to be different.
When I run npm run serve: the generated path should be http://0.0.0.0:8080/app.js (so that the file is served by npm and I can have hot reload etc.)
When I run npm run build: the generated path should be http://0.0.0.0:8000/static/app.js (so that django can serve the file. please note the port number 8000, not 8080)
So I'm wondering if there's a way for vue.config.js to have 2 versions, one that would be used by serve the other one by build.
I know this question is like two years old.
Use the absolute path for the environment variable VUE_CLI_SERVICE_CONFIG_PATH.
You could use $PWD to instead current absolute path.
// package.json
"scripts": {
"serve": "vue-cli-service serve",
"serve:test": "env VUE_CLI_SERVICE_CONFIG_PATH=\"/var/www/html/your_project/vue.config_serve_test.js\" vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
npm run serve:test will use vue.config_serve_test.js
npm run build will use vue.config.js

Removing log statements in Create React App without ejecting

I use lots of console.log() statements while developing Apps (and I mean LOTS). How exactly can I remove them without "ejecting" from a
Create React App
What I considered but not sure how exactly to implement:
In my package.json:
"build": "react-scripts build && uglifyjs --compress drop_console build/static/js/main.xxxxx.js -o build/static/js/main.xxxxx.js
However How exactly can I know the hash suffix on the main.js file so I can call this command and save the output js file with same filename
Add this to index.js
if (process.env.NODE_ENV !== 'development') {
console.log = () => {}
}
Note that this will only suppress the messages, it will not strip them from your deployed code.
Note Nov 2020
Don't do this for library modules, it will disable console.log for the parent project.
Update Sept 2020
There is some movement on this issue on the CRA repo... go give it support/thumbs up here https://github.com/facebook/create-react-app/pull/9222
References:
How to quickly and conveniently disable all console.log statements in my code?
If you just want to suppress log output you could wrap console.log and use that instead
const log = (...msgs) => {
if (process.env.NODE_ENV === 'development') console.log(...msgs)
}
You can import / export this, but that sounds like a pain. Seems like a good thing to add to global
global.log = log
global.log('will only log in dev')
Do this in package.json scripts:
"build": "./scripts/build.sh"
and then in your project:
scripts/build.sh looks like:
#!/usr/bin/env bash
set -e;
cd "$(dirname $(dirname "$BASH_SOURCE"))" # cd to project root
react-scripts build
for f in build/static/js/*.js; do
uglifyjs --compress drop_console "$PWD/$f" -o "$PWD/$f"
done
You can try this combo of packages to override the config:
Note: from the document of react-app-rewired, this would break the the "guarantees" that CRA provides. So you should be careful before using it.
npm i -D customize-cra react-app-rewired babel-plugin-transform-remove-console
Modify your package.json, replace react-scripts to react-app-rewired except the reject. Once complete, your scripts should look like this:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
Then create a file under the root directory:
touch config-overrides.js
// config-overrides.js
const { override, addBabelPlugins } = require('customize-cra')
module.exports = override(
addBabelPlugins(
"transform-remove-console"
)
)
Finally, after running npm run build, all console.log gone.
I use this setup. I still need console log while in dev.
// config-overrides.js
const { override, addBabelPlugins } = require('customize-cra')
module.exports = override(
process.env.NODE_ENV !== 'development' && addBabelPlugins(
"transform-remove-console"
)
)

Deploy NextJS with Dokku in Production

I have set up Dokku and want to deploy my basic NextJs to it. Everything works fine, except for that the application is running in development mode.
When I output the NODE_ENV variable in my JSX, it is first production but changes to development.
const Index = () => (
<div>
<Link href="/about">
<a>About Page</a>
</Link>
{process.env.NODE_ENV}
</div>
That's what I am seeing. The NODE_ENV variable changes during the page load.
package.json:
"scripts": {
"start": "next src",
"build": "next build src"
},
App.json:
{
"scripts": {
"dokku": {
"predeploy": "npm run build"
}
}
}
Procfile:
web: npm start -- --port $PORT
In addition I set two configs for my dokku application:
dokku config:set my-app NPM_CONFIG_PRODUCTION=false
dokku config:set my-app HOST=0.0.0.0 NODE_ENV=production
What am I missing to get it into production mode?
Solved it by setting up an own express server.
package.json
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
app.json
{
"scripts": {
"dokku": {
"predeploy": "npm run build"
}
}
}
Procfile
web: npm start -- --port $PORT
According to this github issue comment you need to have the application listen to the PORT environment variable.
I could not get this to work though. There are examples of how you can get a npm-script to consume environment variables, but I didn't want to go down that road just now. (see this question for more info on that.)
However, I did notice that Next.js listen to port 3000 by default, and dokku uses port 5000 internally, so I got it to work by simply changing the default npm start script to next -p 5000, that is I hardcoded the Next.js app to use port 5000.
This works for now, but I've only tested it with a clean, minimal project, so not sure if there are other blockers down the road.
Also, it seems like Next.js does in fact pick up on env variables from .env files, but that isn't reflected in the port the app is served on for some reason:

npm: How to set NODE_ENV in Windows (10)?

I am trying to add an npm script in package.json that sets NODE_ENV before doing something else (like running webpack). But although the syntax seems to be correct, NODE_ENV is not set when running under Windows 10.
Test script
"scripts": {
"test": "SET NODE_ENV=debug && echo %NODE_ENV%" }
The result from npm run test is "production" (provided NODE_ENV was set to "production" before running the script). Should be "debug".
What could be wrong? I even tried cross-env with no success.
Edit
To clarify my question: I cannot set any environment variable under Windows 10. And I need to call SET because I am running the script under Windows (10). Seems to be some rights problem (scripts not allowed to set environment variables?).
Another (or the actual) question would be: How can I create one script to build (using webpack) with creating minified versions of JavaScript files (for production), and one script to create non-minified versions (for development). So far I use following approach (see comments for the important parts):
Edit 2
I did not now that this probably made a difference, but in case it does: I worked with an React app created with create-react-app. I found the answer to my question, see below.
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// Scipts for build for development and for production
"build-dev": "SET NODE_ENV=debug webpack",
"build-release": "SET NODE_ENV=production webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"debug": "^2.6.4",
"webpack": "^2.4.1"
}
}
webpack.config.js:
const path = require('path');
var webpack = require('webpack');
// Check if in debug environment
var debug = process.env.NODE_ENV !== "production";
module.exports = {
context: path.join(__dirname, 'src'),
entry: ['./index.js'],
output: {
path: path.join(__dirname, 'www/js'),
filename: 'index.js',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}],
},
// Add the UglifyJs plugin only in debug mode
plugins: debug ? [] : [new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false })],
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
This fails because setting NODE_ENV does not work for some reason. Using the command prompt directly like in the scripts:
SET NODE_ENV = debug
webpack
works by the way. That's proof that the configuration is okay, but just the npm script cannot set NODE_ENV.
Just in case you are STILL having issues setting the NODE_ENV in Windows 10 - this will help you. In your package.json file add the following:
"test": "SET \"NODE_ENV=test\""
If you plan on pushing this to Heroku - you will have to "export" the variable and your string would look like this (you are escaping the Windows-NEEDED quotes with a slash):
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\""
Lastly, if you need a following command like mocha then the line would look like this:
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha server/**/*.name_of_files_plus_test.js"
Hope this helps someone :) - Mike
I found the answer to my question in the meantime, basically in the create-react-app readme: Firstly in an app created with create-react-app NODE_ENV cannot be manually overridden. Secondly, when setting environment variables, their name must start with "REACT_APP_". This was the solution for me.
In package.json:
"scripts": {
...
"build:staging": "SET REACT_APP_ENVIRONMENT=Staging && npm run build"
}
In the code:
if (process.env.REACT_APP_ENVIRONMENT === "Staging") ...
Did you try?
set DEBUG=* & npm run test
Make sure debug already installed
npm install debug --save
UPDATE:
To set environment variable in windows use
set NODE_ENV=dev //for development environment
In your case
"scripts": {
"test": "NODE_ENV=dev && echo %NODE_ENV%" }

webpack-dev-server does not watch for my file changes

When I change my files while webpack-dev-server is running, the bundle's files are not updated.
Here are my webpack.config.js and package.json files, as you can see from my npm script, I've solved running webpack watch and webpack-dev-server in the same command (npm run watch & webpack-dev-server --content-base ./ --port 9966):
webpack.config.js:
'use strict';
var ReactStylePlugin = require('react-style-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {
devtool: 'sourcemap',
entry: ['./js/main.js'],
output: {
filename: 'bundle.js',
path: __dirname + '/assets',
publicPath: __dirname + '/'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: [
ReactStylePlugin.loader(),
'jsx-loader?harmony'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css-loader')
}
]
},
plugins: [
new ReactStylePlugin('bundle.css'),
new webpack.DefinePlugin({
'process.env': {
// To enable production mode:
//NODE_ENV: JSON.stringify('production')
}
})
]
}
package.json:
{
"name": "reactTest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack",
"web": "npm run watch & webpack-dev-server --content-base ./ --port 9966"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.10.1",
"extract-text-webpack-plugin": "^0.3.8",
"jsx-loader": "^0.13.1",
"react-style-webpack-plugin": "^0.4.0",
"style-loader": "^0.10.2",
"url-loader": "^0.5.5",
"webpack": "^1.8.5",
"webpack-dev-server": "^1.8.0"
},
"dependencies": {
"react": "^0.13.1",
"react-style": "^0.5.3"
}
}
my directory structure is:
assets
bundle.css
bundle.css.map
bundle.js
bundle.js.map
js
AppActions.js
Profile.css.js
ProfileList.js
main.js
AppConstants.js
AppStore.js
Profile.js
ResultPage.js
package.json
index.html
node_modules
webpack.config.js
every file inside assets directory is generated by webpack
In order to get webpack to watch my file changes (Ubuntu 14.04), I had to increase the number of watchers (I had increased the number before, but it was still too low):
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Source in the official docs: https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers
I first suspected the cause to be fsevents which doesn't work on Ubuntu, but this apparently wasn't the case.
Furthermore, because now the watching and re-compiling worked, but the automatic browser refresh part didn't work, I added the --inline param to the answer of #deowk which enables the "inline mode":
webpack-dev-server --content-base ./ --port 9966 --hot --inline
Quote from the official docs: "The easiest way to use Hot Module Replacement with the webpack-dev-server is to use the inline mode."
Source: https://webpack.github.io/docs/webpack-dev-server.html#hot-module-replacement
you need to run webpack-dev-server with the --hot flag:
webpack-dev-server --content-base ./ --port 9966 --hot
Then you can access the hot-loading version localhost:9966/webpack-dev-server/
You don't need to run watch as well.
update:
This entry in your webpack config must change:
entry: ['./js/main.js'], --> entry: ['webpack/hot/dev-server' , './js/main.js']
Change your publicPath entry:
publicPath: '/assets/'
#funkybunky identified the right problem but (IMHO) fixed it the wrong way. At least in my case, webpack was trying to watch every file it used, including a deep chain of thousands of files of dependencies pulled from npm. I added this to my config, per the docs:
devServer: {
watchOptions: {
ignored: /node_modules/
}
}
Of course you legitimately could have thousands of files that might need to be watched, in which case go ahead and raise the limit, but you're probably better off ignoring vendor libraries that aren't likely to change.
I'll put this here just in case it helps anyone. My problem was the same, but caused by inconsistent capitalization of directory names and webpack alias declaration.
I had a WebGL directory which i referenced in my aliases as webgl, and unfortunately this worked for the build, but didn't work for code watching.
In my case, the error was caused by an empty space in the directory name, by changing "Repository Name" by "RepositoryName", everything worked fine !
Figured I'd post my solution as well. I had the same problem getting Flutter apps to run on OS X due to my hard drive setup.
The gist is if your project folder is in a symlinked folder, detecting the file changes may not work on OS X. Previously, we were on Webpack 3.X, I believe, and live reload/refresh worked fine in the original folder. However, after upgrading to the latest Webpack (^5.75.0) and Webpack Dev Server (^4.11.1), the hot-reloading no longer worked for me.
My original project folder was:
/Users/blakemiller/h/somefolder/v2/my-widget
The "/h" there is a symlink to: /System/Volumes/Data/projects/home/web/
I'm not sure what happened when I upgraded OS X at some point, but the upgrade changed the folders in a way that I don't really understand.
Putting the folder here instead, fixed the issue for me (no symlink):
/Users/blakemiller/my-widget
I doubt this will work for many people, as my setup is probably pretty specific, but maybe it will help someone else save 5 hours down the road...