Next.js env file depending deployment stage - next.js

Let's say I am deploying Next.js in different env, for example.
local development
staging deployment
production deployment
Previously I hand used .env file with one of the framework where I could easily name the file like .env.local, .env.stage & .env.prod and when I run node app locally it would load .env.local, with export STAGE=stageframework would use.env.stage`, like wise fro productoin.
Is that such support in Next js where I can have different .env file for different stage. If it is supported then how would I specify which stage Next.js is running.

You can have different environments, just need to follow this
For production
// .env.production.local
// This file is for production and run with next start or npm run start
// NODE_ENV=production
For development
// .env.development.local
// This file is for development and run when next dev or npm run dev
// NODE_ENV=development
For tests
// .env.test.local
// This file is for tests with jest or cypress for example
// NODE_ENV=test
If you want know more about this, here is the complete info about environments in next js
Update:
If you want to run more environments without next standard, you can do this manually:
// package.json
"scripts": {
...
"dev:staging": "APP_ENV=staging next dev",
}
...
// next.config.js
require('dotenv-flow').config({
node_env: process.env.APP_ENV || process.env.NODE_ENV ||
'development',
});
const env = {};
Object.keys(process.env).forEach((key) => {
if (key.startsWith('NEXT_PUBLIC_')) {
env[key] = process.env[key];
}
});
module.exports = {
env,
};
And when you run npm run/yarn dev:staging your staging environment from .env.staging.local will be loaded, my reference is from flybayer and you can read more here

Related

Next js standalone mood not optimizing images?

I am create a next build with standalone output. I follow this answer- How to deploy NextJs (SSR) using "Output File Tracing" feature to Azure App Service?
After setting up I run my server like this node server.js
It works perfectly. But here image optimization not working. I found one error-
Error: 'sharp' is required to be installed in standalone mode for the image optimization to function correctly
I recheck package.json and I can see sharp is already installed. Then I add this to my .env file-
NEXT_SHARP_PATH=/tmp/node_modules/sharp
But not working. Please any help me. I need image opmization feature in standalone mood.
***Note: I use linux subsystem on windows. In linux subsystem, When I run production mode npm run start. Image optmization automatically work in this mode, I haven't to give .env also. When I start my project in standalone mood, image optimization is not working. Even when I give .env it's not working.
Here is my next.config.js-
/** #type {import('next').NextConfig} */
const withPWA = require("next-pwa")({
dest: "public",
register: true,
disable: process.env.NODE_ENV === "development"
});
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
output: "standalone",
images: {
minimumCacheTTL: 2592000,
domains: ["dzzoo94ozikw5.cloudfront.net", "lh3.googleusercontent.com", "platform-lookaside.fbsbx.com"]
},
}
module.exports = withPWA(nextConfig)
yarn add sharp
or
npm install sharp
https://nextjs.org/docs/messages/sharp-missing-in-production

Running grunt sub task inside a custom module

I'm building a grunt module to help me to initialize, create default folder/files and build some WebProjects. I create a custom Grunt module including some custom tasks.
So My module is oshell.grunt and inside this module I've a task InitializeLibrary. This InitializeLibrary is a custom task that request some input from the user before creating the files/folder structure. I use grunt-prompt for this.
My problem is when I run the custom module inside my main project, the task prompt is not found. Can you please share your experience regarding this because I suppose some developers were faced to the same problem
Custom module structure
oshell.grunt
tasks
InitializeLibrary.js
After installing the custom module inside the Main projects
Main projects
oshell.core
node_modules
oshell.grunt
tasks
InitializeLibrary.js
It seems to be ok.
InitializeLibrary.js
module.exports = function(
grunt
){
"use strict";
grunt.initConfig({
"prompt": {
"libraryInfo": {
options: {
questions: [
{
config: "InitializeOpenShellLibrary.version",
type: "input",
message: "Initial version of the library",
default: "0.1.0"
}
]
}
}
}
});
require("load-grunt-subtasks")(grunt);
grunt.registerTask(
"InitializeLibrary",
[
"prompt:libraryInfo"
]
);
}
Main web project grunt file
module.exports = function(
grunt
){
"use strict";
grunt.loadNpmTasks("oshell.grunt");
grunt.registerTask("default", ["InitializeLibrary"]);
};
When I run this grunt in my main project I get this result.
Warning: Task "prompt:libraryInfo" not found. Use --force to continue.
I expected the task prompt to run inside the custom module for having a prompt for the library information.
Thanks a lot for your answers guys.
please install https://www.npmjs.com/package/grunt-prompt and add this code in grunt config file:
grunt.loadNpmTasks('grunt-prompt');

Importing "gitlab" package from MeteorJS returns empty object

I've installed gitlab in my Meteor project with meteor npm install --save gitlab and imported the package in the imports/api/foo.js file with all the following variations (the comment on the front is the log of the Gitlab object):
import Gitlab from 'gitlab'; // {}
import * as Gitlab from 'gitlab'; // { default: {}, [Symbol(__esModule)]: true }
import { Gitlab } from 'gitlab'; // undefined
const Gitlab = require('gitlab'); // {}
const Gitlab = require('gitlab/dist/es5'); // {}
const Gitlab = require('gitlab/dist/latest'); // {}
If I run just console.log(require('gitlab')) with NodeJS, I get the correct result.
How am I supposed to import 'gitlab' from a meteor application?
I tried to reproduce the issue with a clean Meteor 1.8.0.2 project and it is working fine for me:
/server/main.js:
import Gitlab from 'gitlab'
Meteor.startup(() => {
console.log(Gitlab) // [Function: Bundle]
const api = new Gitlab({
url: 'http://example.com', // Defaults to https://gitlab.com
token: 'abcdefghij123456' // Can be created in your profile.
})
console.log(api) // full API as in documentation
})
So what options do you have here?
Make sure you use gitlab on the server
Check the node_modules folder, whether it is really installed there.
Try to reset your project using meteor reset and then start again so all node_modules a rebuild and all Meteor packages are rebuild and the local dev build is rebuild. This will often fix things.
Create a fresh project and start to reproduce the issue step by step, starting from my working example and change the file structure stepwise to the structure of your project.

Error with Firebase on Electron app: Failed to load gRPC

I'm building an Electron app, and in the renderer.js file, I'm using Firebase Admin to get Firestore data. However, whenever I run it, it returns this error in the logs..
Error: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: electron-v2.0-darwin-x64-unknown
Found: [node-v48-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
I tried to run "npm rebuild", but it still didn't fix it.
I also tried updating Firebase Admin and gRPC.
Here is the code from the renderer.js file...
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const admin = require('firebase-admin');
var serviceAccount = require('./credentials.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mytestapp.firebaseio.com"
});
var db = admin.firestore();
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
function LoadList() {
db.collection("Orders").get().then(function(Collection){
Collection.forEach(function(OrderDoc){
console.log(OrderDoc.id)
})
}).catch(function(err){
console.error(err);
});
}
document.querySelector('#ListSec').addEventListener('click', LoadOrderList)
Any ideas? I've been trying to solve this for hours, but can't seem to figure it out.
That error message indicates that gRPC was installed for Node, not for Electron. Electron has a different binary interface, so binary modules like gRPC need to be installed specifically for Electron. You can generally do this just by running npm rebuild --runtime=electron --target=2.0.0 (modified to match the version of Electron you want to use).
The original answer by #murgatroid99 was helpful at the time, and a postinstall command worked great up until electron v7, where the issue returned.
For anyone else who comes across this issue, I've found a better solution:
the electron-rebuild package
npm install electron-rebuild --save-dev
Run it using
npx electron-rebuild
Or, add it as a postinstall command
{
...
"scripts": {
"postinstall": "electron-rebuild"
},
...
}
Further information is in the official Electron Documentation

Is there any way to tell angular-cli (for angular 2) to generate minified version of css?

As the title says, when I run "ng serve" angular-cli generates normal css whereas I expect to get the minified version.
Is there any specific setting to use for angular-cli-build, or some additional plugin to install and use?
This is my angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(ts|js|js.map)',
'rxjs/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)',
'angular2-cookie/**/*.js'
]
});
};
ng build --prod --env=prod
or
ng serve --prod
Will minify and add a file hash for you.
the --prod tells it to minify hash, and gzip.
the --env=prod tells it to use your prod environment constants file.
which would look like this
You can use
# --env=<your_env>
# --no-sourcemap
# minify => ./minify.js
ng build --env=prod --no-sourcemap && node minify
minify.js
// npm i --save-dev minifier fs-jetpack
const jetpack = require('fs-jetpack');
const path = require('path');
const minifier = require('minifier');
const files = jetpack.list(path.join(__dirname, 'dist'));
console.log(files);
for (const file of files) {
if (/.*(\.js|\.css)$/g.test(file)) {
console.log(`Start ${file}`);
const filePath = path.join(__dirname, 'dist', file);
minifier.minify(filePath, {output: filePath});
}
}
console.log('End');
James' commands DO work and DO minify even when using ng serve --prod.
However you may see something like the following in Chrome and get confused:
That doesn't look minified does it!
Look more carefully and you'll see js:formatted indicating that the pretty print feature was enabled.
Opening the URL http://localhost:4200/main.5082a3da36a8d45dfa42.js directly in a new tab showed me that the CLI was indeed minifying it fully.
You can click the {} icon to turn this feature off, but it seems to like to disappear once the code has been pretty printed so you may need to reload the page and click it quickly.
In 2020 it is just enough to use --prod flag, when building project:
ng build --prod

Resources