How to get env variables from env in github action .yaml in Vite project - vue.js

I want to set an environment variable in github action .yaml. And I can access that variable inside my Vite project run time.
Exp:
# staging.yaml - my github action file
...
env: VITE_INTERNAL = true
...
// index.vue - my Vite project
function myTest(){
console.log(process.env.VITE_INTERNAL) // I hope to get "true" instead of "undefined"
}
Anyone can help me, please. Thanks a lot!

To set an environment variable in a GitHub Action YAML, you can use env, jobs.<job_id>.env, or jobs.<job_id>.steps[*].env:
name: Build
permissions:
contents: read
issues: read
checks: write
pull-requests: write
on: push
# 👇 global env
env:
VITE_INTERNAL: true
jobs:
build:
runs-on: ubuntu-latest
# 👇 or job-level env
env:
VITE_INTERNAL: true
steps:
- uses: actions/checkout#v3
- uses: actions/setup-node#v3
with:
node-version: 18.x
cache: 'npm'
- name: Install dependencies
run: npm i
- name: Build
run: npm run build
# 👇 or step-level env
env:
VITE_INTERNAL: true
To access the environment variable from JavaScript, use import.meta.env.VITE_INTERNAL (not process.env.VITE_INTERNAL).
GitHub demo

You can read the docs here, but to expose env variables, you can do it like the following.
.env
VITE_INTERNAL = true
.yaml
console.log(import.meta.env.VITE_INTERNAL)

Related

Semantic release not publishing correct folder

For the past few days, I'm trying to publish my package to github by using semantic-release. Unfortunately, I can't publish the correct folder as source code (zip) file in my npm package hosted on github.
My github action pipeline:
on:
push:
branches:
- main
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
defaults:
run:
working-directory: ./frontend
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v3
- uses: actions/setup-node#v3
with:
node-version: 18
cache: 'npm'
cache-dependency-path: ./frontend
- name: Install packages
run: npm install
- name: Build frontend
run: npm run build
- name: Copy json file to dist dir
run: cp package.json ./dist
- name: Run semantic release and publish package
run: |
cd ./dist
pwd
npm run semantic-release
It's supposed to publish the dist folder, but I see the whole project directory as the source code output to npm. It's not publishing my build folder. When I run pwd, I'm on the correct path: /home/runner/work/test/test/frontend/dist
Semantic-release is also not respecting my property in my package.json file:
"files": [
"/dist"
]
I specifically want to output the dist folder, but unfortunately, everything is in the output folder except the dist folder.
I also tried adding a pkgRoot property to to the '#semantic-release/npm' module, but still! No dist folder being published.
['#semantic-release/npm', { 'pkgRoot': './dist' }],
What can be the issue of this problem?
I was also having this issue yesterday and this is what worked for me. Notice that I omitted a lot of configuration stuff from the files mentioned not to "bloat" the answer. Let me know if this works for you!
package.json
Remove the "files" key.
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rm -rf dist && tsc --project tsconfig.build.json && cp package.json dist/package.json",
}
semantic-release/npm configuration
"#semantic-release/npm", { "pkgRoot": "./dist" }],
semantic-release/git configuration
[
"#semantic-release/git",
{
"assets": [
"package.json",
"README.md",
"CHANGELOG.md",
"dist/**/*.{js}"
],
"message": "chore: Release ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
]
tsconfig.json
"compilerOptions": {
"rootDir": "src",
"outDir": "./dist",
}

How to configure Cypress for e2e in Github Actions?

I am trying to do an e2e test on my VueJS app that uses axios for API calls. In my vue component, in the mounted, i do an API call. My idea would be to mock this call with cy.intercept and cy.wait, however i can't make it work. On my local environment when i launch my frontend and backend servers, my test passes as the API call is made. However, the call is not silenced and the cy.wait('#apiCall') does not work.
Also my test does not work in Github Actions, i have this error : AxiosError: The following error originated from your application code, not from Cypress. It was caused by an unhandled promise rejection.. I have the impression that github actions need a special ci environment file but i don't know where to tell cypress to look into those env variables when in continous integration.
Anyone had the same issue or knows about cypress X axios X github actions combined ?
Some of my code :
test.cy.js
cy.intercept('GET', '/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')
cy.visit('/hello?coach=30283')
cy.wait('#getCoach')
component.vue
async mounted() {
await axios.get(`/coaches/coach-informations/30283/`)
}
.env
API_URL=http://127.0.0.1:8000/api
test-frontend.yml
name: GitHub Actions Demo
on: [pull_request, push]
jobs:
cypress-run:
runs-on: ubuntu-latest
env:
working-directory: front
steps:
- name: Checkout
uses: actions/checkout#v3
- name: Install node
uses: actions/setup-node#v3
with:
node:version: 'node-version'
- name: Get yarn cache directory path 🛠
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
working-directory: ${{env.working-directory}}
- name: Cache node_modules 📦
uses: actions/cache#v2.1.7
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-${{ hashFiles('front/yarn.lock') }}
restore-keys: |
yarn-
- name: Install dependencies 👨🏻‍💻
working-directory: ${{env.working-directory}}
run: yarn
- name: Cypress run
uses: cypress-io/github-action#v2
with:
working-directory: ${{env.working-directory}}
build: yarn build
start: yarn vite
wait-on: 'http://localhost:3000'
wait-on-timeout: 120
config-file: cypress.config.js
record: true
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
I would say the URL used in the intercept is not catching the request from the app.
Locally you have a server running, so axios is ok but on Github the server is absent and the axios call fails.
It looks like you just need to add wildcard characters before the URL fragment
cy.intercept('GET', '**/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')

Prevent Vercel Deployment on branch push

I have my GitHub Repository linked to my vercel project. Required for deploying changes on a subdomain that's linked to a branch on my git repository. dev.<website>.<tld> is linked to the dev branch. <website>.<tld> is linked to the main branch. Couldn't figure out another way to do this, other than linking to my git repo.
I have a GitHub action that runs tests amongst other things that I want to ensure pass before deployment. But every time I push changes to my production branch it kicks of a vercel deployment, that I want to avoid.
I know there is a Ignored Build Step section in the git settings on vercel, but I'm not sure what to add in the command input in this section?
I've added
[ exit 1 ]
But not sure if this is correct.
Here is my github actions workflow yml file.
name: Deploy Web Application
on:
push:
branches: ["master", "development"]
paths:
- "web/**"
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./web
strategy:
matrix:
node-version: [16.13.0]
steps:
- name: Checkout
uses: actions/checkout#v3
- name: Node Version ${{ matrix.node-version }}
uses: actions/setup-node#v3
with:
node-version: ${{ matrix.node-version }}
cache: "yarn"
cache-dependency-path: "./web/yarn.lock"
- name: Install Dependencies
run: yarn
- name: Build Project
run: yarn build
- name: Run Linting
run: yarn lint
- name: Run Typecheck
run: yarn typecheck
- name: Start Deployment
uses: bobheadxi/deployments#v0.6.2
id: deployment
with:
step: start
token: ${{ secrets.GH_TOKEN }}
env: prod
- name: Deploy to Vercel
uses: amondnet/vercel-action#v20
id: vercel-action
with:
github-token: ${{ secrets.GH_TOKEN }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
# if main branch go to --prod environment otherwise nothing for preview environment
vercel-args: "${{ github.ref == 'refs/heads/master' && '--prod' || '' }}"
working-directory: ./web
- name: Update Deployment Status
uses: bobheadxi/deployments#v0.6.2
if: always()
with:
step: finish
token: ${{ secrets.GH_TOKEN }}
status: ${{ job.status }}
deployment_id: ${{ steps.deployment.outputs.deployment_id }}
env_url: ${{ steps.vercel-action.outputs.preview-url }}
You can enable the "Ignored Build Step" field by referring to the
documentation of this feature. If the command returns "0", the
build will be skipped. If, however, a code "1" or greater is
returned, then a new deployment will be built.
With a Script
#!/bin/bash
echo "VERCEL_ENV: $VERCEL_ENV"
if [[ "$VERCEL_ENV" == "production" ]] ; then
# Proceed with the build
echo "✅ - Build can proceed"
exit 1;
else
# Don't build
echo "🛑 - Build cancelled"
exit 0;
fi
With Environment Variables
#!/bin/bash
echo "VERCEL_GIT_COMMIT_REF: $VERCEL_GIT_COMMIT_REF"
if [[ "$VERCEL_GIT_COMMIT_REF" == "staging" || "$VERCEL_GIT_COMMIT_REF" == "main" ]] ; then
# Proceed with the build
echo "✅ - Build can proceed"
exit 1;
else
# Don't build
echo "🛑 - Build cancelled"
exit 0;
fi
With Folders and Workspaces
To build a new deployment considering only a certain folder, you can use the following command:
git diff HEAD^ HEAD --quiet ./packages/frontend/
The above was copied from here (includes more details):
How do I use the "Ignored Build Step" field on Vercel?
Video tutorial:
How to Ignore Build Step on Vercel
Another guide:
Vercel – ignore GitHub branches

How to use github actions bot for testing gradle java

I am trying to implement Github-actions(bot), which runs gradle test when PR has been created.
To assure that my workflow file works as I expected, I explicitly wrote a test method which should cause failure.
#Test
fun thisShouldFail() {
assertEquals(1, 2)
}
When I try testing on my local machine, I get the log below.
> Task :test FAILED
FAILURE: Build failed with an exception.
# More
Above log indicates that there was something wrong in the test codes as I expected it to be.
But then Github actions bot runs this command, the test code result is SUCCESS.
Below is my github workflow yaml file for this action.
name: PullRequestGradleTest
on:
pull_request_target:
types: [labeled]
jobs:
test:
name: GradleTest
runs-on: ubuntu-latest
if: contains(github.event.pull_request.labels.*.name, 'STAGING')
steps:
- name: checkout
uses: actions/checkout#v2
- name: Setup JDK 1.8
uses: actions/setup-java#v2
with:
java-version: '8'
distribution: 'adopt'
- name: Grant Permissions to gradlew
run: chmod +x gradlew
- name: Test
run: gradle test --tests "*"
- name: Test Success
if: success()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "All tests passed.",
event: "APPROVE"
})
- name: Test Fail
if: failure()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "There is something wrong with test codes.",
event: "REQUEST_CHANGES"
})
await github.pulls.update({
...context.repo,
pull_number,
state: "closed"
})
I found that you are using gradle, not gradlew.
name: PullRequestGradleTest
on:
pull_request_target:
types: [labeled]
jobs:
test:
name: GradleTest
runs-on: ubuntu-latest
if: contains(github.event.pull_request.labels.*.name, 'STAGING')
steps:
- name: checkout
uses: actions/checkout#v2
- name: Setup JDK 1.8
uses: actions/setup-java#v2
with:
java-version: '8'
distribution: 'adopt'
- name: Grant Permissions to gradlew
run: chmod +x gradlew
- name: Test
run: ./gradlew test --tests "*"
- name: Test Success
if: success()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "All tests passed.",
event: "APPROVE"
})
- name: Test Fail
if: failure()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "There is something wrong with test codes.",
event: "REQUEST_CHANGES"
})
await github.pulls.update({
...context.repo,
pull_number,
state: "closed"
})
If you use gradle in the command, it will depend on the machine's environment. In this case, there is a possibility that occurs error because of Gradle version. Therefore, you need to use the project's Gradle which is included with your repo. The way to use is using gradlew scripts.
I also recommend following these three steps to test the branch for the pull request.
Clean -> Assemble(or build) -> Test
Base problem was that if we use pull_request_target event, the action runs on the target branch, which would be the base branch that the PR will be merged into. To solve this problem, I had to explicitly set where this action will run on.
On job => steps
steps:
- name: checkout
uses: actions/checkout#v2
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{github.event.pull_request.head.repo.full_name }}

travis ci publishing to npm only when PR is merged on master

I'm trying to publish to npm only when a PR is merged on master but the deploy never runs. any help?
language: node_js
node_js:
- "node"
jobs:
include:
- stage: test
script:
- npm test
- stage: deploy
provider: npm
email: $NPM_EMAIL
api_key: $NPM_API_TOKEN
skip_cleanup: true
stages:
- name: test
- name: deploy
if: (type = push) AND (branch = master)
This took me a while to figure out so I'm posting my answer in case anyone else runs into same issue.
language: node_js
node_js:
- "node"
script: npm test
deploy:
provider: npm
email: $NPM_EMAIL
api_key: $NPM_API_TOKEN
skip_cleanup: true
on:
condition: $TRAVIS_EVENT_TYPE = push #this was the fix
#tags: true
branch: master