How to get the -p argument value in Next.js? - javascript

If my Nexs.js app is started with
yarn dev
Where package.json defines it as
{
"scripts": {
"dev": "next dev -p 4000"
}
}
How I get this 4000 value from the -p switch?
Because process.env.PORT is not set this way.
const getBaseUrl = () => {
if (typeof window !== 'undefined') return ''; // browser use relative path
// How to replace the ???? with the value of -p, defaulting to 3000 if not set
return 'http://localhost:????'; // dev SSR should use localhost
}

Related

NodeJS dynamically environment variable setup

I create a NodeJS server and trying to setup environment variables dynamically. But I'm facing a weird problem. I create a env.js file and here is the related code:
const environment = {}
environment.dev = {
port: 3000,
envName: 'dev'
}
environment.prod = {
port: 5000,
envName: 'prod'
}
const currentEnvironment = typeof process.env.NODE_ENV === 'string'
? process.env.NODE_ENV
: 'dev'
console.log('current environment: ', currentEnvironment) // get currentEnvironment: prod
console.log('environment obj: ', environment) // get environment obj correctly
console.log('getting obj from environment obj: ', environment[currentEnvironment]) // But get undefined
const environmentToExport = typeof environment[currentEnvironment] === 'object'
? environment[currentEnvironment]
: environment.dev
module.exports = environmentToExport
I can't figure out why I'm getting undefined in environment[currentEnvironment].
And here is the package.json scripts from where I'm passing environment variable. I'm using windows by the way.
"scripts": {
"dev": "SET NODE_ENV=dev & nodemon index",
"prod": "SET NODE_ENV=prod & nodemon index"
}
Note: I'm using exported port number while creating server. But incase of getting undefined, I'm always exporting dev environment ! Hope you understand my problem.

Add craco webpack plugin by condition for create react app

I am using craco with create react app and I would like to add a plugin only in DEV mode or by ENV Var
my craco.config looks is:
const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = () => {
return {
webpack: {
alias: {
environment: path.join(
__dirname,
'src',
'environments',
process.env.CLIENT_ENV || 'production'
)
}
// plugins: [new BundleAnalyzerPlugin()]
},
jest: {
configure: {
testPathIgnorePatterns: ['<rootDir>/src/environments/'],
moduleNameMapper: {
environment: '<rootDir>/src/environments/test'
}
}
}
};
};
so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE_ENV=test
while I trying to push to plugin array I got that plugin I undefined
module.exports.webpack.plugins.push(plugin)
You can set an environment variable right before any script command. For example, in your package.json, add a new line in the scripts paragraph that sets some variables:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"analyzer": "env NODE_ENV=production ANALYZER=test yarn start"
}
In craco.config.js you can simply use:
plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : []
Now, running npm run analyzer will both, set node env to production, set a variable ANALYZER to test (used later on) and load the craco config, that will start both the webpack server and the analyser.
you can use conditions from craco like when, whenDev, whenProd, whenTest
webpack: {
plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},

how to create exe package of angular electron app

I have developed an app in angular 6. I am trying to make .exe build using electron. When I am making an electron build in the dev environment which is working fine but now I want to release a package for windows I have installed electron packager on my machine trying to make a build for windows. I have installed wine on Linux machine to run the build. It is making the build of the app but when I run .exe file it displays me an empty window. I don't understand what the issue is & why it is displaying me an empty screen.
// main.ts
const { app, BrowserWindow } = require('electron')
const path = require('path');
let win;
function createWindow () {
win = new BrowserWindow({
width: 600,
height: 600,
backgroundColor: '#ffffff'
})
win.maximize()
win.loadURL(`file://${__dirname}/dist/task-reporting-tool/index.html`)
win.on('closed', function () {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (win === null) {
createWindow()
}
})
// package.json
"main": "main.js",
"description": "task-reporting-tool",
"files": [ "build", "*.js", "public"],
"scripts": {
"electron": "electron .",
"electron-build": "ng build --prod && electron .",
"packager": "electron-packager . WinApp --platform=win32 --arch=all"
}
index.html
<base href="./">
I have created a main.js file. done changes in the index.html file & in package.json.
Using npm run packager to make a build. All the required changes are done build successful but displays an empty screen.
Install npm and then try:
electron-packager . --asar
electron-packager . --all
You could try :
win.loadURL(
url.format({
pathname: path.join(__dirname, "/dist/angular-electron/index.html"),
protocol: "file:",
slashes: true
})
);

Abort npm build script from node.js script

I created a node script which checks if my project contains lock file or not. If it doesn't then I want to abort my npm build. Any idea how to do that?
lock-check.js
const path = require('path');
const fs = require("fs");
const lockFiles = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock"];
let exists = 0;
function checkIfExists() {
lockFiles.forEach(
(lf) => {
if (fs.existsSync(lf)) {
exists++;
}
});
return exists > 0;
}
package.json
...
"scripts": {
"prestart": "node ./lock-check.js" // Abort the task
"start": "webpack-dev-server --config config/webpack.dev.js --hot --inline"
}
...
To abort the build process you just have to call process.exit(1),
Here I have used 1 but you can use any non-zero exit code to tell it wasn't a successful build as 0 means successful.
You can read more on official nodejs docs

Set gulp tasks depending on NODE_ENV

Is there a way to specify a gulp task depending on the NODE_ENV that is set?
For example in my package.json file, I have something like:
"scripts": {
"start": "gulp"
}
And I have multiple gulp tasks
gulp.task('development', function () {
// run dev related tasks like watch
});
gulp.task('production', function () {
// run prod related tasks
});
If I set NODE_ENV=production npm start, can I specify to only run gulp production? Or is there a better way to do this?
Using a single ternary in your default gulp task, you can have something like:
gulp.task('default',
[process.env.NODE_ENV === 'production' ? 'production' : 'development']
);
You will then be able to keep the single gulp command in your package.json and using this like you said:
NODE_ENV=production npm start
Any other value of your NODE_ENV variable will launch the development task.
You could of course do an advanced usage using an object allowing for multiple tasks and avoiding if trees hell:
var tasks = {
development: 'development',
production: ['git', 'build', 'publish'],
preprod: ['build:preprod', 'publish:preprod'],
...
}
gulp.task('default', tasks[process.env.NODE_ENV] || 'fallback')
Keep in mind that when giving an array of tasks, they will be run in parallel.
Have your first gulp task run other gulp tasks based on the process.env.NODE_ENV value.
gulp.task('launcher', function(){
switch (process.env.NODE_ENV){
case 'development':
// Run dev tasks from here
break;
case 'production':
// Run prod tasks
break;
}
});
The other simple way could be
gulp.task('set-dev-env', function () {
return process.env.NODE_ENV = 'development';
});
gulp.task('set-prod-env', function () {
return process.env.NODE_ENV = 'production';
});
gulp.task('development', ['set-dev-env'], function () {
// your code
});
gulp.task('production', ['set-prod-env'], function () {
// your code
});
Run gulp production or gulp development.
You can also use gulp-mode plugin.
Usage:
var gulp = require('gulp');
var mode = require('gulp-mode')();
var uglify = require('gulp-uglify');
gulp.task('default', function() {
gulp.src('src/*.js')
.pipe(mode.production(uglify()))
.pipe(gulp.dest('dist'));
});
OR
var isProduction = mode.production();
if (isProduction) {
console.log("Production mode");
}
Start build as:
gulp build --production
For "npm run-script" use-cases:
package.json :-
"scripts": {
"devbld": "gulp build --development",
"prodbld": "gulp build --production",
}
$ npm run devbld
$ npm run prodbld
if (process.env.NODE_ENV === "production")
// whatever

Categories