How to only run a gulp.task locally? - javascript

I have the following gulp function:
// TODO: Comment for production.
gulp.task('startServer', function() {
return connect.server({
root: './dist',
port: 8080
});
});
Every time I pull it to work on it locally, I have to uncomment the code and then comment it back when I push to prod. I have to do something similar to this in a few files. Is there a clever way to avoid this hassle and being able to pull/push code without having to comment/uncomment all of this for every single branch I work on?
Thanks.

You don't need to use gulp code to start server . You can run local and production server using express nodejs.

On your production server, the NODE_ENV environment variable should be set to production (NODE_ENV=production). So you can add a conditional to your gulp file to check whether you are running it on the production server or not:
if (process.env.NODE_ENV !== 'production') {
gulp.task('startServer', function() {
return connect.server({
root: './dist',
port: 8080
});
});
}

Related

How to run code depending on whether its running on live website or localhost?

I'm new to coding. I have a node.js application which I have deployed using "Heroku.com". I want to use a custom domain for the application as well as having SSL active using the custom domain. When the application uses the default domain given by Heroku, SSL is automatically in place, however if I want SSL to work when I use a custom domain, I have to include the following code in my app.js file in order for SSL to work:
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https')
res.redirect(`https://${req.header('host')}${req.url}`)
else
next()
});
This works fine, however when I am maintaining my app locally (in VS Code) and use localhost:3000 for testing purposes I have to comment out the code above in order to be able to view the app using locahost because of something to do with localhost not working with HTTPS.
So my question is, is there a code (if statement or something of the like) that will run that code if its being used in a live environment or to not run if its being used in localhost. This is mainly so I don't have to continue to comment out the code before and after deployment and testing.
If you have any other advice or better solutions for this kind of thing I would appreciate it.
Cheers,
Sam
You can use the concept of environment variables to differentiate between the production enviroment (live website on heroku) and the development environment (localhost). Specifically, you can set an environment variable NODE_ENV (just a popular naming convention, nothing in-built) to a value that can be used inside your code logic to perform actions based on the environment.
You can access the value by writing
const env = process.env.NODE_ENV;
Note: You have to set the environment variable first, otherwise process.env.NODE_ENV is just going to be undefined.
How to set the environment variables?
There are a couple of ways, like having a .env file, passing through CLI, etc. I'll show you a quick way. While running your server on localhost, write this,
NODE_ENV=development node server.js
Now, inside your server.js, you can do something like
// If NODE_ENV is undefined, assume production
const env = process.env.NODE_ENV || 'production';
app.use((req, res, next) => {
if (env === 'production' && req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`)
}
else {
next()
}
})
You can have as many environments as you like (development, testing, production, staging, etc.) Also check out dotenv module
[Edit]
Create folder called config inside add settings.js
package.json
app.js
--config // Will hold your configuration settings
----settings.js // Your settings
In settings.js
const settings = {
development: {
// Developpment configuration settings
email: 'development#gmail.com'
},
staging: {
// staging settings
email: 'staging#gmail.com'
},
production: {
// Production configuration settings
email: 'production#gmail.com'
},
}
const getSettings = () => {
if (!process.env.NODE_ENV) return settings.development
if (process.env.NODE_ENV === 'staging') return settings.staging
return settings.production
}
module.exports = getSettings()
what is proccess.env.NODE_ENV? It's an enviroment variable which if you didn't declare will return undefined and you can make it's variable different by setting it from the terminal
When you go to development try to run this command in the hoster terminal
export NODE_ENV=production
DON'T RUN THIS IN YOUR LOCAL TERMINAL, try to ask your web hosters how to run a command in their command line to store environment variable
for heroku: heroku run export process.env.NODE_ENV
DON'T WRITE ANY SENSITIVE DATA THERE! store them in environment variables too
Also for the port you would want to do something like this in your app.js
const port = process.env.PORT || 3000

How do I set up AWS Cloud9 to run an existing JavaScript app with webpack-dev-server (in development mode)?

I am trying to get my fairly typical JavaScript (React) app to run in dev mode on AWS Cloud9. I successfully cloned my repo (using https ugh), installed my npm packages, and can run scripts in the console. However, I don't know how to run and access the app in dev mode. There are a plethora of docs but they all seem to dance around the running part. My guess is I need to somehow set a custom host and port, but I also need to find what URL to use to see the app running.
Here is my devServer config:
devServer: {
// Display only errors to reduce the amount of output.
stats: "errors-only",
host, // Defaults to `localhost`
port, // Defaults to 8080
overlay: {
errors: true,
warnings: true,
},
}
If anyone comes across this, I wanted to share my solution because I know how frustrating this can be:
First, create a script in your package.json file:
"start": "webpack-dev-server --open"
Then, add the following to your Webpack config file:
devServer: {
contentBase: path.join(__dirname, 'dist'),
host: '0.0.0.0',
port: 8080,
compress: true,
}
Then, open the terminal in AWS Cloud 9, and run the script:
npm start
Finally, click on the link in the terminal: "Project is running at http://0.0.0.0:8080/" and your app will show in a new window.
**If it doesn't work, don't forget to allow port 80 on your Cloud 9 Security Group: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule
If you want to view the project in the preview pane, you can add the following to your devServer config:
disableHostCheck: true,
However, it's important to note that when set to true, this option bypasses host checking. THIS IS NOT RECOMMENDED as apps that do not check the host are vulnerable to DNS rebinding attacks.
1) First thing you need to do is to run react app on port 8080. You can do this by setting environment variable PORT to 8080 and then just starting react dev server from AWS Cloud9 terminal.
export PORT=8080
npm start
For details look at this discussion on GitHub.
2) After starting your application you can preview it by clicking Preview -> Preview Running Application at the top of AWS Cloud9.
For more details check this AWS Cloud9 doc
In webpack.config.js:
devServer: {
historyApiFallback: true,
contentBase: './',
host: process.env.IP,
//https: true,
port: process.env.PORT,
"public": "your-project.c9users.io" //no trailing slash
},
Refer Link

Browser-sync not watching files

I am having problems with browser-sync. When I first installed, it was working, but now it no longer refreshs my index page when I make modifications to it and save. I noticed that when I start browser-sync, it no longer show the "[BS]Watching files..." message.
Have I missed any steps?
Prompt output
Just add the command "--watch" when using the command line.
Like this:
browser-sync start --server --watch --files "*"
Blisk browser was a great option, as suggested by Darren, but now it is paid.
Got browser sync working with gulp as suggested by this discussion https://github.com/BrowserSync/browser-sync/issues/646
Config:
gulp.task('browserSync', function() {
browserSync.init({
open: 'external',
host: 'coolab.dev',
proxy: 'coolab.dev/dashboard',
port: 3000
});
});

Grunt dev server to allow push states

I am trying to set up my grunt server to allow push states.
After countless google searches and reading SO posts I cannot figure out how to do this.
I keep getting errors like the one below.
Does anyone have any ideas how to fix this?
No "connect" targets found. Warning: Task "connect" failed. Use --force to continue.
It appears to me below that I have defined targets with the line
open: {
target: 'http://localhost:8000'
}
See complete code below:
var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
options: {
hostname: 'localhost',
port: 8000,
keepalive: true,
open: {
target: 'http://localhost:8000'
},
middleware: function (connect, options) {
return [
// Rewrite requests to root so they may be handled by router
pushState(),
// Serve static files
connect.static(options.base)
];
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify'); // Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-connect'); // Load the plugin that provides the "connect" task.
// Default task(s).
grunt.registerTask('default', [ 'connect']);
};
Push states are already included in most SPA frameworks, so you might not need this unless you're building a framework.
Angular: https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag
React: How to remove the hash from the url in react-router
This looks like a grunt build script to compile an application to serve. So I'm not exactly sure how you'd use pushStates in the build process. You may be trying to solve the wrong problem.
Don't bother with grunt to deploy a local dev pushstate server for your SPA.
In your project directory, install https://www.npmjs.com/package/pushstate-server
npm i pushstate-server -D
Then to launch it, add a script entry in the package.json of your project:
…
"scripts": {
"dev": "pushstate-server"
}
…
This way you can now start it running npm run dev
All the requests which would normally end in a 404 will now redirect to index.html.

Gulp Connect not running server

I created the gulpfile.js and in it has a use for gulp-connect
gulp.task('connect', function(){
connect.server({
root: 'dev',
livereload: true,
port: 8000
});
})
When I run gulp connect it does not maintain my server on localhost:8000.
[14:08:51] Starting 'connect'...
[14:08:51] Server started http://localhost:8000
[14:08:51] LiveReload started on port 35729
[14:08:51] Finished 'connect' after 13 ms
Hence I get nothing when opening up http://locahost:8000
What can I do to make connect work and create a server to deploy my html?
I had the same problem and I resolved it by having more than one file in the served folder (my dist directory). I don't know why it works but it started working after that.
I used the following settings:
gulp.task('connect', function(){
connect.server({
root: ['dist'],
port: 8000,
base: 'http://localhost',
livereload: true
});
I use v2.2.0 of gulp-connect.
gulp-connect has been deprecated.
You may wish to use the rewritten package called gulp-webserver.

Categories

Resources