Install Gatsby in the /blog directory - github

I created a Gatsby blog using the Netlify one-click button but wish to have my own home landing page using index.html and then then the Gatsby blog be built in the /blog directory of my site (example.com/blog)
I have looked into the config.js and gatsby-config.js files for settings to change the build location plus I have also tried a few different build commands in Netlify such as
Build command : gatsby build
Publish directory: public/articles
Can anyone help build this in a specific folder(directory) whilst leaving my own index.html in the root directory?

Have a look at this starter and have a read of Gatsby tutorial Part 7
gatsby-node.js
const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))
const { createFilePath } = require(`gatsby-source-filesystem`)
const path = require("path")
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `blog` })
createNodeField({
node,
name: `slug`,
value: replacePath(slug),
})
}
}
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions
const postTemplate = path.resolve(`src/templates/postTemplate.js`)
return graphql(`
{
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
limit: 1000
) {
edges {
node {
fields {
slug
}
}
}
}
}
`).then(result => {
if (result.errors) {
return Promise.reject(result.errors)
}
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: replacePath(node.fields.slug),
component: postTemplate
})
})
})
}
Here in onCreateNode, if the node's internal type is MarkdownRemark, a filepath is created with a base path of blog, and that new filepath is added to a new node field called slug.
This new field is now available in any graphQL queries.
So later in createPages, the new slug field is queried and used in the createPage path option.
So pages in your src/blog folder will remain to be served from the root, while posts generated by MarkdownRemark will be served from /blog/

In gatsby-config.js add this
module.exports = {
pathPrefix: `/blog`,
and while you building your app:
gatsby build --prefix-paths

You’ll need to tell Gatsby where you want the file. Netlify just wants to know where your public folder is.
gatsby build --output-dir public/articles
You can either then move your own index.html file into the directory created (public), or have it already there*.
I would also recommend looking at letting Gatsby run your whole site, and create a static file for your homepage, then your build process is much simplier, and you can run it locally.
* Not sure if that is allowed, Gatsby may require an empty or non-exisiting folder to build into.

Related

How to deploy an generate a static site on Nuxt 3

Hello I'm creating website on Nuxt and i have created a new app on Nuxt 3. But I have an probleme for the deployement, there is no 'normal' build for 'normal server' as Nuxt 2.x.
I'm using 'Lamdba' preset.
https://v3.nuxtjs.org/docs/deployment/presets/lambda
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt3'
// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
// Global page headers: https://go.nuxtjs.dev/config-head
nitro: {
preset: 'lambda'
},
head: {
title: 'Title',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }
],
link: [
{ rel: 'icon', type: 'image/png', href: '/favicon.png' }
],
script: [
{
type: 'text/javascript',
src: '/mana.js',
}
]
},
})
And on Nuxt 2.x I used this :
// nuxt.config.js
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
// Target: https://go.nuxtjs.dev/config-target
target: 'static'
}
What configuration i should to use on Nuxt 3 to have 'normal' export with an index.html file at the root for all server ?
Please use generate script like yarn generate this will create the .output/public and output will depend on ssr: boolean property in nuxt.config.ts.
if ssr is true which is by default, then there will be individual html for each dynamic route and that means dynamic routes are rendered at build time and whenever there is change in data or number of dynamic routes then you will need to run this command again.
if ssr is false then rendering will be done at client side, like SPA app and dynamic routes will have only one file that will do client side rendering and data will be fetched at client side that way site will show latest data.
Check static-hosting
Static deployment is not currently available for Nuxt 3
Besides adding target: 'static' in your nuxt.config.ts
export default defineNuxtConfig({
target: 'static' // default is 'server'
})
You also need to update your build script to be nuxi generate in your package.json (which was nuxi build originally)
{
"scripts": {
"build": "nuxi generate"
}
}
References: https://v3.nuxtjs.org/bridge/overview#static-target
I managed to deploy my nuxt3 project static to gh-pages. I had to overcome two obstacles.
yarn generate did not generate static routes until I explicitly forced it by setting
generate: {routes: ['/','all','my','other','routes']} ....
in nuxt.config.js as target:"static" did not work for me.
gh-pages need an empty .nojekyll file which seems currently not being generated by nuxt generate nor gh-pages. I entered the following into my package.json:
"deploy": "touch .output/.nojekyll && gh-pages --dotfiles -d .output"
This seems ugly but works for me.

NextJS PWA Service worker map 404 in Production

I am trying to build a PWA with NextJS and this https://www.npmjs.com/package/next-pwa
It have been working fine in development, but know i try to build and run it in production.
It seems like the files below only is being build when i run it as dev and is thereby missing in the prod build.
enter image description here
Is this an error in my config?
module.exports = withImages(
withPWA({
pwa: {
dest: 'public'
},
env: {
apiUrl: process.env.API_URL
},
webpack: (config, { isServer }) => {
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
})
)
Please help!

Connect Gatsby with Postgres

I would like to pull data from Postgres to Gatsby using graphql. I have written node.js server, but i cannot find way to use it in gatsby.
(https://github.com/gstuczynski/graphql-postgres-test)
Have you any ideas?
What you need to do is implement a source plugin as seen here https://www.gatsbyjs.org/docs/create-source-plugin/.
There are many examples within the gatsby repository that implement the source api. See those for inspiration! Basically you need to translate the contents of your Postgres db into a format gatsby understands. Gatsby calls this format “nodes”.
You could implement a plugin which interfaces with your db directly or with whatever api your node server exposes (graphql, REST etc.).
The gatsby-source-pg module connects directly to your database and adds the tables/views/functions/etc to Gatsby's GraphQL API. To use it, install the module:
yarn add gatsby-source-pg
then add to to the plugin list in gatsby-config.js:
module.exports = {
plugins: [
/* ... */
{
resolve: "gatsby-source-pg",
options: {
connectionString: "postgres://localhost/my_db",
},
},
],
};
The connection string can also include username/password, host, port and SSL if you need to connect to remote database; e.g.: postgres://pg_user:pg_pass#pg_host:5432/pg_db?ssl=1
You can query it in your components using the root postgres field, e.g.:
{
postgres {
allPosts {
nodes {
id
title
authorId
userByAuthorId {
id
username
}
}
}
}
}
Gatsby now supports an arbitrary GraphQL endpoint as a source which will help: https://www.gatsbyjs.org/packages/gatsby-source-graphql/
You can also use Hasura to give you an instant GraphQL API on Postgres and then query that from your Gatsby app. You can follow the tutorial here.
Step1: Deploy Hasura against your existing Postgres database: https://docs.hasura.io/1.0/graphql/manual/getting-started/using-existing-database.html
Step 2: Install the gatsby-source-graphql plugin for gatsby: https://www.gatsbyjs.org/packages/gatsby-source-graphql/
Step 3: Configure the plugin
{
plugins: [
{
resolve: 'gatsby-source-graphql', // <- Configure plugin
options: {
typeName: 'HASURA',
fieldName: 'hasura', // <- fieldName under which schema will be stitched
createLink: () =>
createHttpLink({
uri: `https://my-graphql.herokuapp.com/v1alpha1/graphql`, // <- Configure connection GraphQL url
headers: {},
fetch,
}),
refetchInterval: 10, // Refresh every 10 seconds for new data
},
},
]
}
Step 4: Make the GraphQL query in your component
const Index = ({ data }) => (
<div>
<h1>My Authors </h1>
<AuthorList authors={data.hasura.author} />
</div>
)
export const query = graphql`
query AuthorQuery {
hasura { # <- fieldName as configured in the gatsby-config
author { # Normal GraphQL query
id
name
}
}
}
Other links:
Sample-app/tutorial:
https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/gatsby-postgres-graphql
Blogpost:
https://blog.hasura.io/create-gatsby-sites-using-graphql-on-postgres-603b5dd1e516
Note: I work at Hasura.

How we can generate html report in cucumber latest version(3.2.0) with protractor-cucumber framework

Since cucumber 3 removed the registerHandler and registerListener , how we can generate html report in cucumber 3.2.0.I have used below code for generating json report in cucumber 2.
defineSupportCode(function({ registerListener }) {
var JsonFormatter = new Cucumber.JsonFormatter();
JsonFormatter.log = function(string) {
var outputDir = 'testreports/report';
var fileName = 'cucumber-report.json';
var targetJson = path.resolve(outputDir, fileName);
if (fse.existsSync(outputDir)) {
fse.moveSync(outputDir, outputDir + '_' + moment().format('YYYYMMDD_HHmmss'), {
overwrite: true
});
}
fse.outputFileSync(targetJson, string);
};
registerListener(JsonFormatter);
});
and used below code for html report
defineSupportCode(function({ registerHandler }) {
registerHandler('AfterFeatures', function(features, callback) {
var options = {
theme: 'bootstrap',
jsonFile: 'testreports/report/cucumber-report.json',
output: 'testreports/report/cucumber-report.html',
reportSuiteAsScenarios: true,
};
reporter.generate(options);
callback();
});
});
Thanks in advance.
You have to do following changes:
1) set cucumberOpts.format in protractor conf file
cucumberOpts: {
format: ["json:reports/report/cucumber/cucumber-report.json"],
here reports/report/cucumber/cucumber-report.json is the cucumber json file path, you must specify a path at here.
framework will generate it automatically with results' json data as file content when all scenarios execute complete.
2) create parent folder of cucumber json file path before test framework load if parent folder not exist
Option 1: put create parent folder code at head of protractor conf file.
Option 2: create a Protractor plugin implement interface: setup(), which will be executed before test framework load.
// plugin: create-report-folder.js
var moment = require("moment");
var fse = require("fs-extra");
module.exports = {
setup: function() {
var reportDir = this.config.options.reportDir;
if (fse.existsSync(reportDir)) {
fse.moveSync(
reportDir,
reportDir + "_" + moment().format("YYYYMMDD_HHmmss"),
{ overwrite: true}
);
}
fse.mkdirsSync(reportDir);
}
};
Note: both options need to use Sync api to create folder.
3) create Protractor plugin implement interface: postResults which will be executeed after all scenarios execute complete.
// plugin: cucumber-html-reporter.js
var reporter = require("cucumber-html-reporter");
module.exports = {
postResults: function() {
var options = {
theme: "bootstrap",
jsonFile: this.config.options.jsonFile,
output: this.config.options.htmlFile,
reportSuiteAsScenarios: true
};
reporter.generate(options);
}
};
Note: I tried generate cucumber html report in cucumber AfterAll hook, but failed, seems Cucumber JsonFormater generate cucumber json file is Async, when AfterAll hook start execute, cucumber json file have not create yet.
I'm keeping look into formatOption, should be a way to change JsonFormater generate cucumber json file to Sync, then we can use AfterAll hook.
4) set plugins in protractor conf file
// protractor conf file
exports.config = {
plugins: [
// plugin to create report parent folder
{
path: "supports/create-report-folder.js",
options: {
reportDir: "reports/report/cucumber"
}
}
// plugin to generate cucumber html report
{
path: "supports/cucumber-html-reporter.js",
options: {
jsonFile: "reports/report/cucumber/cucumber-report.json",
htmlFile: "reports/report/cucumber/cucumber-report.html"
}
}
]
A workable scaffold for Protractor + Cucumber4 + HTML Report at my github
The scaffold for Protractor + Cucumber3 + HTML Report on my local has some dependency campatible issue, I'm looking into that in case you must use Cucumber 3.
5) If you use multiCapabilities, you can use below package to generate report:
protractor-multiple-cucumber-html-reporter-plugin
If the location of protractor.conf.js is not at the same level as node_modules then the cucumberOpts.format path would be relative to its current file location and the protractor-multiple-cucumber-html-reporter-plugin looks for the json files relative to parent root folder and warns about json file is not found.
To solve this provide absolute path of the json file to cucumberOpts.format like below. This is applicable if you're using cucumber for e2e testing in Angular applications where the protractor.conf.js is normally present inside e2e folder.
cucumberOpts: {
require: [path.resolve(process.cwd(), 'e2e/steps/*.ts')],
format: 'json:'+ path.resolve(process.cwd() + '/reports/cucumber-ui-reports.json')
}

How to serve a static folder in sails.js?

I want to serve a folder app, which is at the same level with assets folder, under the url /app.
It's possible with AppController to serve file according the url, but I want to know whether it is possible to do this like the following with express?
app.use(express.static(__dirname + '/public'));
You can use custom middleware for express in sails by adding it to your config/http.js:
var express = require('express');
module.exports.express = {
customMiddleware: function (app) {
app.use(express.logger());
app.use(express.compress());
app.use('/app', express.static(process.cwd() + '/../client/www/'));
}
};
Off the top of my head, there's two choices:
Create a symlink assets/app pointing to your destination. The resources should be accessible via http://your.host.com/app/* since that's the way Sails serves assets.
There's still Express underneath Sails, you should be able to access it with sails.express.app and do your thing, let's say, from config/bootstrap.js:
var express = require('express');
…
sails.express.app.use(express.static(process.cwd() + '/app'));
I'm using Sails.js v0.12.4. The http.js uses module.exports.http and not module.exports.express I did the following to serve up another folder like the existing /assets folder. In my example to serve up the app folder, replace the 'node_modules/bootstrap/dist' path with /app
In the config/http.js file I added
var express = require('express');
Then in the middleware object I added the express static module. I'm wanting to serve up the bootstrap assets contained in my node_modules folder.
bootstrapAssets: express.static('node_modules/bootstrap/dist'),
Then in the order array, I added the 'bootstrapAssets' in the order I wanted this middleware to run. Here is the full code:
var express = require('express');
module.exports.http = {
middleware: {
passportInit : require('passport').initialize(),
passportSession : require('passport').session(),
bootstrapAssets : express.static('node_modules/bootstrap/dist'),
order: [
'startRequestTimer',
'cookieParser',
'session',
'bootstrapAssets',
'passportInit',
'passportSession',
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'www',
'favicon',
'404',
'500'
],
Now in my HTML I can access the the bootstrap css using the following:
<link rel="stylesheet" href="/css/bootstrap.min.css">
In Sails 1.0 you can modify the file config/routes.js and add this:
var express = require('express')
var serveStatic = require('serve-static')
var os = require('os')
const dir = `${os.homedir()}/foo` // dir = /home/dimas/foo
module.exports.routes = {
'/public/*': serveStatic(dir, {skipAssets: true}), // <-- ADD THIS
'/': {
controller: 'FooController',
action: 'checkLogin'
},
};
Then you have to create the directory structure:
/home/dimas/foo/public
NOTE that the public entry (the route) is INCLUDED in the filesystem path, the files to be served must be placed there!
After that you can access any content by hitting the following URL:
http://localhost:1337/public/foratemer.txt
You can serve your files simple like this:
var express = require('../node_modules/sails/node_modules/express');
module.exports.express = {
middleware: {
custom: true
},
customMiddleware: function (app) {
app.use(express.logger());
app.use(express.compress());
app.use('/api/docs',express.static('assets/swagger-ui/dist/'));
}
};
This is my config/express.js file
You can use this for sails 0.12.3:
Install express to your sail: npm install express --save
After that, modify config/route.js
module.exports.routes = {
...
'/public/*': require('express').static('the-directory-that-contains-public-director')
...
}
This will works. However, it is a bit ugly that you have to create a directory as a parent for your public directory. It is because the static middleware create by express will count the '/public/' prefix in calculating to path to the target files.
Sails v1.0: Serve a file with a . dot folder in sails. Example: https://myWebSite.com/.well-known/test.txt
in the config/http.js file add express.static to serve and then add publicFolder in the order array.
module.exports.http = {
middleware: {
publicFolder: express.static('public/public'),
order: [
'cookieParser',
'session',
'publicFolder'
// 'favicon',
],
}}
Create a public folder and .well-known folder so public/.well-known/test.txt