How to pass `--` when used with pre npm scripts - bash

How to pass others flags into npm command that has pre config
"prebuild": "npm run build:vendor",
"build": "cross-env NODE_ENV=production webpack --env.production -p",
When I run npm run build -- --env.produciton the flag --env.produciton does not work
I want to pass into webpack command.. ending like this
cross-env NODE_ENV=production webpack --env.production -p --env.production

two options to pass params, one over node cross-env:
"build": "cross-env NODE_ENV=production YOUR_ENV=yourName webpack -p"
if (process.env.YOUR_ENV === 'yourName') { }
the other with webpack:
"build": "webpack --env.NODE_ENV=local --env.YOUR_ENV yourName --progress"
const path = require('path');
module.exports = env => {
// Use env.YOUR_ENV here:
console.log('YOUR_ENV: ', env.YOUR_ENV); // 'yourName'
return {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
};
The param is always true if you won't set value.
https://webpack.js.org/guides/environment-variables/
Setting up your env variable without assignment, --env.production sets --env.production to true by default..

Related

Custom Node server causes Nextjs to fail to load 'No `pages` directory found'

I'm trying to bootstrap a new Nextjs app, and for integrating with Auth0 I need my localhost to be running HTTPS. I followed the guide here (https://medium.com/responsetap-engineering/nextjs-https-for-a-local-dev-server-98bb441eabd7), and generated a local certificate which is in more trusted certificate store.
To use HTTPS for localhost, you apparently need to create a custom server (this seems an odd oversight on the Nextjs side), so here's my custom server:
const { createServer } = require('https');
const { parse } = require('url');
const next = require('next');
const fs = require('fs');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, dir: __dirname });
const handle = app.getRequestHandler();
const httpsOptions = {
key: fs.readFileSync('./certificates/ReactDevCertificate.key'),
cert: fs.readFileSync('./certificates/ReactDevCertificate.cer'),
};
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(3000, (err) => {
if (err) throw err;
console.log('> Server started on https://localhost:3000');
});
});
Now, previous without the custom server, the app loads fine. But, with the custom server, it fails to load:
➜ yarn run dev
yarn run v1.22.15
$ next dev ./server.js
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: > No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?
at Object.findPagesDir (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\lib\find-pages-dir.js:31:15)
at new DevServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\dev\next-dev-server.js:110:44)
at NextServer.createServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:102:20)
at C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:117:42
at async NextServer.prepare (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:92:24)
at async C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\cli\next-dev.js:126:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
It feels like somewhere the app has navigated to a child folder, as there is code in the function find-pages-dir.js (https://github.com/vercel/next.js/blob/canary/packages/next/lib/find-pages-dir.ts#L22) that looks specifically to the parent directory for the pages folder.
For reference, here is my package.json:
{
"name": "fictionist-ui",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev ./server.js",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.0.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.4"
},
"devDependencies": {
"#types/node": "16.11.6",
"#types/react": "17.0.33",
"eslint": "7.32.0",
"eslint-config-next": "12.0.1",
"typescript": "4.4.4"
}
}
OS: Windows 11
NPM: 16.9.0
Yarn: 1.22.15
My mistake was that I didn't get the command right:
"scripts": {
"dev": "node server.js" // was "next dev ./server.js"
}

Pass environment variable through PM2 to NextJS

I have 2 package.json scripts that look like this:
"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",
And an ecosystem.config.js that looks like this:
module.exports = {
apps: [
{
name: 'test.co.uk',
script: 'npm',
args: 'start',
env_staging: {
API: 'staging',
NODE_ENV: 'production',
PORT: 3001,
},
},
],
};
I then run the following:
TEST_VAR='test' npm run pm2_staging
I would expect the following to happen:
The PM2 restart command fires
ecosystem.config.js fires the npm start command and sets some environment variables
The app starts and all env vars are available, including TEST_VAR (set in the original command)
What actually happens is all the env vars from the ecosystem are correctly set, but TEST_VAR is not available in the app. Why is this and how do I go about setting secret keys from CI tools if I can't do this?
I ran into the same problem tonight. After looking every where I found the config needed. The env variable needs to go in your ecosystem.config.js like below. In my case I put it at the root of my server
module.exports = {
apps : [{
name: 'nextjs',
script: 'yarn',
args:"start",
cwd:"/var/www/myapp/",
instances: 2,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production',
API_URL: 'YOUR ENV URL',
PORT:8000
}
}]
};
package.json like so
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start -p 8000"
},
...
and executed something like this
#!/bin/bash
cd /var/www/myapp/
git pull && yarn install && yarn build
cd ~/
pm2 start ecosystem.config.js --env production
Then the API_URL would be available in const API_URL = process.env.API_URL in your app.
These urls helped
https://willandskill.se/en/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04/
https://pm2.keymetrics.io/docs/usage/application-declaration/
Another idea would be passing all the env parameters of PM2 to the server via the following.
ecosystem.config.js being:
module.exports = {
apps: [{
name: "my-service-1",
script: "dist/server.js",
env_production: process.env, // pass all the env params of the container to node
}],
};
#webface
The environment variables in your example will not be available in Nextjs. To be available to both the client and server, variables must be prefixed with NEXT_PUBLIC (ie. NEXT_PUBLIC_API_VERSION).
These environment variables must be passed into the build process to be available at runtime.

Heroku Deployment Error: displaying backend, not frontend

I am trying to deploy my local MERN application to Heroku. Application works offline. After deployment, when click "Open app", all I see is the data from the backend. Not the front end. Deployment here: https://whispering-falls-45660.herokuapp.com/.
Set up new Heroku project, and after successful "git push Heroku master", application only shows backend data. Heroku CLI version: heroku/7.24.1, Node version: v10.13.0.
Github repo: https://github.com/neilhsieh/whereToEat
Package.json file has the proper scripts in place as per Brad Traversy:
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
server.js code has appropriate code to point to client build file:
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')) // relative path
})
}
Expecting front end deployed on Heroku, ended up only having backend.
UPDATE: Moved process.env.NODE_ENV test to before all API calls, this fixed my issue.
First if you have a route like this in your server/app.js file
app.get("/", (req, res) => res.send("Api Running"));
Definitely get rid of that
Second add these lines in your server/app.js file
const path = require("path");
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}

Unable to use Elixir after upgrade

I upgraded my Elixir version from 3.0 to 5.0. The npm update command runs fine but when I try to run gulp --production it fails.
I have given the error below which I get.
My package.json file (which should be identical to the one at https://github.com/laravel/laravel/blob/master/package.json)
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"gulp": "^3.9.1",
"laravel-elixir": "^5.0.0",
"bootstrap-sass": "^3.3.0"
}
}
When running gulp --production I get the below error
/home/vagrant/Code/laravel/node_modules/laravel- elixir/node_modules/gulp- cssnano/node_modules/cssnano/node_modules/postcss/lib/lazy-result.js:157
this.processing = new Promise(function (resolve, reject) {
^
ReferenceError: Promise is not defined
at LazyResult.async (/home/vagrant/Code/laravel/node_modules/laravel-elixir/node_modules/gulp-cssnano/node_modules/cssnano/node_modules/postcss/lib/lazy-result.js:157:31)
at LazyResult.then (/home/vagrant/Code/laravel/node_modules/laravel-elixir/node_modules/gulp-cssnano/node_modules/cssnano/node_modules/postcss/lib/lazy-result.js:79:21)
at Transform.stream._transform (/home/vagrant/Code/laravel/node_modules/laravel-elixir/node_modules/gulp-cssnano/index.js:27:17)
at Transform._read (_stream_transform.js:179:10)
at Transform._write (_stream_transform.js:167:12)
at doWrite (_stream_writable.js:226:10)
at writeOrBuffer (_stream_writable.js:216:5)
at Transform.Writable.write (_stream_writable.js:183:11)
at write (/home/vagrant/Code/laravel/node_modules/laravel-elixir/node_modules/gulp-concat/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:623:24)
at flow (/home/vagrant/Code/laravel/node_modules/laravel-elixir/node_modules/gulp-concat/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:632:7)
You need to upgrade Node also.
You can read here how it can be updated upgraded: https://askubuntu.com/questions/426750/how-can-i-update-my-nodejs-to-the-latest-version

Dev dependencies needed for Heroku webpack build

I was under the impression that I wouldn't need the devDependencies to be included when I deploy to Heroku a react based app, using Webpack. For example, here's my package.
"scripts": {
"test": "",
"start": "./node_modules/.bin/babel-node server",
"build": "rimraf dist && export NODE_ENV=production && webpack --config ./webpack.production.config.js --progress --profile --colors",
"postinstall": "node deploy",
"eslint": "eslint .",
"jscs": "jscs ."
},
and deploy.js:
if (process.env.NODE_ENV === 'production') {
var child_process = require('child_process');
child_process.exec("webpack -p --config webpack.production.config.js", function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
}
and the Procfile
web ./node_modules/.bin/babel-node server.js
However, when I push to Heroku, I'm constantly getting a webpack command not recognized, so I included all of the devDependencies as normal dependencies to have it working. Am I missing something here?
Heroku set NPM_CONFIG_PRODUCTION to true by default to install dependencies only. If you would like to install devDependencies, you can disable production mode:
$ heroku config:set NPM_CONFIG_PRODUCTION=false
However, since you usually don’t want all devDependencies in your production builds, it’s preferable to move only the dependencies you actually need for production builds into dependencies (bower, grunt, gulp, etc).

Resources