Goal
I want to get rid of some folders before the electron-forge's packaging step, because the option ignore.roge.config in package.json does not get rid of all the intermediate folders that I specify to ignore for some packages. Those intermediate folders are usually generated during a native build process during packaging.
Problem
But adding hooks field with the documented events don't seem to work, e.g.,
having a package.json field like this seems to add nothing to the equation, i.e., I don't see the expected console log.
"config": {
"forge": {
"packagerConfig": {
"icon": "src/images/myapp",
"ignore": [
"/.gitignore",
"/.vscode",
"/yarn.lock",
"/node_modules/mydep/build/",
"/node_modules/mydep/prebuilds/linux*"
]
},
"hooks": {
"prePackage": "async () => {\"console.log("this is prepackage step.");\"} "
},
"makers": [
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin",
"win32"
]
}
]
}
},
Referring to a related elctron-forge github issue, I've also tried to feed a JS source file to hooks
"hooks": "require:./hooks.js",
where the hooks script looks like
{
prePackage: async () => {
console.log('this is prepackage step.');
}
}
This didn't work either.
Worse, I can't even specify multiple hooks this way:
{
generateAssets: async () => {
console.log('We should generate some assets here');
},
prePackage: async (forgeConfig, options) => {
console.error('lbn: prePackage');
}
}
The above code gives me the following error when running yarn make:
An unhandled error has occurred inside Forge:
Unexpected token ':'
/path/to/myapp/hooks.js:5
prePackage: async (forgeConfig, options) => {
^
SyntaxError: Unexpected token ':'
at wrapSafe (internal/modules/cjs/loader.js:1116:16)
at Module._compile (internal/modules/cjs/loader.js:1164:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Module.require (internal/modules/cjs/loader.js:1089:19)
at require (internal/modules/cjs/helpers.js:73:18)
at renderConfigTemplate (/path/to/myapp/node_modules/#electron-forge/core/src/util/forge-config.ts:100:20)
at _default (/path/to/myapp/node_modules/#electron-forge/core/src/util/forge-config.ts:145:3)
at /path/to/myapp/node_modules/#electron-forge/core/src/api/make.ts:96:19
error Command failed with exit code 1.
Question
What is the right way to specify hooks?
Solved it myself.
We should place the hooks as a normal global module
// ./hooks.js
const fs = require('fs');
const path = require('path');
module.exports = {
postPackage: async (forgeConfig, options) => {
console.warn('\n\npostPackage: exclude files ...\n\n');
}
}; // module.exports = {
Then refer to it in package.json
"hooks": "require:./hooks.js",
Related
I am trying to create a cli tool to make a todo list. For some reason I can't figure out I'm unable to use either require or import when trying to import the Chalk package for highlighting terminal outputs
here is what I have for my index.js file
#! /usr/bin/env node
const { program } = require("commander");
const list = require("./commands/list.js");
program.command("list").description("List all the TODO tasks").action(list);
program.parse();
Here is my list.js file
#! /usr/bin/env node
const conf = new (require("conf"))();
const chalk = require("chalk");
function list() {
const todoList = conf.get("todo-list");
if (todoList && todoList.length) {
console.log(
chalk.blue.bold(
"Tasks in green are done. Tasks in yellow are still not done."
)
);
todoList.forEach((task, index) => {
if (task.done) {
console.log(chalk.greenBright(`${index}. ${task.text}`));
} else {
console.log(chalk.yellowBright(`${index}. ${task.text}`));
}
});
} else {
console.log(chalk.red.bold("You don't have any tasks yet."));
}
}
module.exports = list;
and my package.json file
{
"name": "near-clear-state",
"version": "1.0.0",
"description": "Tool to let NEAR users clear the state of their account ",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "commonjs",
"author": "Dorian",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"near-api-js": "^0.44.2"
},
"bin": {
"near-clear-state": "./index.js"
}
}
when I try running anything from this cli tool I'm making I get this error if I use require
➜ near-clear-state near-clear-state --help
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4
const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/node_modules/chalk/source/index.js from /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js not supported.
Instead change the require of index.js in /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4:15)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14) {
code: 'ERR_REQUIRE_ESM'
}
Or this error when i use import
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:3
import { Chalk } from "chalk";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Node.js v17.4.0
Please help me
Use the import syntax, and add "type": "module" into your package.json to allow for ES6 imports.
I try to learn GraphQL. I wanted to try out the code that is in the Getting Started With GraphQL.js section in the graphql.org. I created a server.js file like this page says: https://graphql.org/graphql-js/
I followed instructions like:
npm init
npm install graphql --save
The package.json file looks like this:
{
"name": "graphql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"graphql": "^16.0.1"
}
}
The server.js file I created looks exactly like the one from the page (it was copied):
var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});
But after using the node server.js command (as written on the page) in the terminal, I get this error:
node_modules\graphql\type\schema.js:35
throw new Error(
^
Error: Expected undefined to be a GraphQL schema.
at assertSchema (F:\GraphQL\node_modules\graphql\type\schema.js:35:11)
at validateSchema (F:\GraphQL\node_modules\graphql\type\validate.js:34:28)
at graphqlImpl (F:\GraphQL\node_modules\graphql\graphql.js:52:64)
at F:\GraphQL\node_modules\graphql\graphql.js:21:43
at new Promise (<anonymous>)
at graphql (F:\GraphQL\node_modules\graphql\graphql.js:21:10)
at Object.<anonymous> (F:\GraphQL\server.js:18:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
Does anyone know what the problem is? Maybe I am missing some package? Or the code given on the page is wrong? Please help me, thank you in advance for any answer.
I am testing building a bundle with rollup using jest which throws error whenever i use async/await. I have no idea what's wrong. I tried different soultions and it's not working.
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at loadCjsDefault (node_modules/#babel/core/lib/config/files/module-types.js:77:18)
at loadCjsOrMjsDefault (node_modules/#babel/core/lib/config/files/module-types.js:49:16)
at loadCjsOrMjsDefault.next (<anonymous>)
at readConfigJS (node_modules/#babel/core/lib/config/files/configuration.js:190:47)
at readConfigJS.next (<anonymous>)
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at _parser (node_modules/#babel/core/lib/parser/index.js:9:16)
at parser (node_modules/#babel/core/lib/parser/index.js:54:18)
at parser.next (<anonymous>)
at normalizeFile (node_modules/#babel/core/lib/transformation/normalize-file.js:93:38)
at normalizeFile.next (<anonymous>)
● Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "TypeError: (0 , _parser(...).parse) is not a function
at parser (D:\projects\js\published\builderz\node_modules\#babel\core\lib\parser\index.js:54:34)
at parser.next (<anonymous>)
at normalizeFile (D:\projects\js\published\builderz\node_modules\#babel\core\lib\transformation\normalize-file.js:93:38)
at normalizeFile.next (<anonymous>)
at run (D:\projects\js\published\builderz\node_modules\#babel\core\lib\transformation\index.js:31:50)
at run.next (<anonymous>)
at Object.transform (D:\projects\js\published\builderz\node_modules\#babel\core\lib\transform.js:27:41)
at transform.next (<anonymous>)
at evaluateSync (D:\projects\js\published\builderz\node_modules\gensync\index.js:244:28)
at Object.sync (D:\projects\js\published\builderz\node_modules\gensync\index.js:84:14) {
code: 'PLUGIN_ERROR',
plugin: 'babel',
hook: 'transform',
id: 'D:\\projects\\js\\published\\builderz\\test\\samples\\pure\\src\\index.js',
watchFiles: [
'D:\\projects\\js\\published\\builderz\\test\\samples\\pure\\src\\index.js'
]
}".
this is test files
import { resolve } from "path";
import builderz from "../src";
jest.useFakeTimers();
describe("production", () => {
it("test pure js", async () => {
await builderz({
isSilent: true,
paths: [resolve(__dirname, "./samples/pure")]
});
// update it later of cource:
expect(true).toEqual(true);
});
});
And babel.config
module.exports = api => {
api.cache(true);
return {
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current"
}
}
]
]
};
};
Add "testEnvironment": "jsdom" into jest key in package.json
"jest": {
"testEnvironment": "jsdom",
"preset": "react-native",
...
In jest.config.js change testEnvironment to testEnvironment: "jsdom" and it should work fine.
PS: Thanks to this answer in Github issue.
I'm using now.sh to deploy my nextjs (React) app. And the build is failing due to this error:
Build error occurred
ReferenceError: describe is not defined
Not sure why this started happening, here is my .babelrc
{
"env": {
"development": {
"compact": false,
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"production": {
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"test": {
"compact": false,
"presets": [
"#babel/preset-typescript",
["next/babel", {"preset-env": { "modules": "commonjs" }}]
],
"plugins": [
["styled-components", { "ssr": true, "displayName": true }],
["#babel/plugin-proposal-decorators", { "legacy": true }],
["babel-plugin-sass-vars"]
]
}
}
}
package.json
"engines" : {
"node" : ">=8.10.0 <11.0.0"
},
"scripts": {
"dev": "NODE_ENV=development next -p 7777",
"build": "NODE_ENV=production next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --no-cache",
"test-watch": "NODE_ENV=test jest --watch --no-cache",
"coverage": "NODE_ENV=test jest --coverage",
"update-snap": "NODE_ENV=test jest --updateSnapshot"
},
Full log:
running "npm run now-build"
> moon.holdings#2.0.0 now-build /tmp/7418164
> next build
Creating an optimized production build ...
> Using external babel configuration
> Location: "/tmp/7418164/.babelrc"
> Build error occurred
ReferenceError: describe is not defined
at Module.kAI8 (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:63996:1)
at __webpack_require__ (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:23:31)
at module.exports.+3sd.exports.__esModule (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:91:18)
at Object.<anonymous> (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:94:10)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
npm
ERR! code ELIFECYCLE
The first test where the describe is used:
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import About from '../about.tsx'
describe('<About /> component', () => {
describe('rendering', () => {
const wrapper = shallow(<About />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
expect(wrapper.contains(<About/>));
});
});
});
next.config
module.exports = (phase, { defaultConfig }) => {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
// Note: Nextjs provides webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
// ✅ Put the require call here.
const withTypescript = require('#zeit/next-typescript')
const withCSS = require('#zeit/next-sass')
// withCSS({target: 'serverless'})
return withTypescript(withCSS({
webpack(config, options) {
return config
}
}))
}
I removed the tests that covered the /pages directory. NextJS used pages for routing. Not sure why that was causing the problem, ran coverage and looks like pages wasn't necessary to cover.
Hoping for a better answer from someone at the NextJS / Now.sh team, and I'll select that.
Easy fix: https://github.com/zeit/next.js/issues/3728#issuecomment-523789071
pageExtensions: ['page.tsx']
An option that allows the tests inside pages folder:
change webpack settings direct in next.config.js
module.exports = {
webpack: (config, { webpack }) => {
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
}
It is ignoring whatever __tests__ folder found on the build process.
If you are looking to colocate non-page files with pages in the /pages directory, you can use Custom Page Extensions to force your pages to have a file extension of .page.js. Once that is setup, Next.js will ignore any files that don't have .page in the file extension.
next.config.js
module.exports = {
// Force .page prefix on page files (ex. index.page.tsx) so generated files can be included in /pages directory without Next.js throwing build errors
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
I wrote some docs for this use case that have yet to be merged https://github.com/vercel/next.js/pull/22740. The docs link above now contains these changes.
The original Github issue where this was discovered is https://github.com/vercel/next.js/issues/3728#issuecomment-895568757.
I am making a POST request to a webservice. The code for POST request is kept in a separate function.The function call from my intent function to the external function is asynchronous.So i am using Promises to achieve synchronicity.The problem here is that when i am importing request-promise-native inside my inline editor it's throwing error as TypeError: Cannot read property 'prototype' of undefined.
But when i tried it in my local workstation which has node js version 9.11.1 it worked fine.The Node JS version in DialogFlow is >=6.0.Is there any other dependency has to be added to it?
Can anyone please explain why this happens?
UPDATE:
I changed the node engine to 6.14.3 and the dependency for the module'request-promise-native' in package.json as "request-promise-native":"v1.0.5".But still no luck.The below is my code:
var doco;
var rp = require('request-promise-native');
var myJSONObject = {
"inputs" : [ {
"name" : "<name>",
"value" : <value>
} ]
};
var orchName = 'TEST05';
postData = JSON.stringify(myJSONObject);
return networkCall(postData,orchName).then((response)=>{
console.log('response is'+response)
console.log("+++++++++++++=DOCO=+++++++++ "+response);
doco = doco1;
//agent.add(`Order number is ${doco1}`);
}).catch((response) => {
console.log(`ERROR: `+response);
});
console.log('doco'+doco);
function networkCall(postData, orchName) {
return new Promise((resolve,reject) =>{
var options = {
method: 'post',
uri: '<URL>',
body: myJSONObject,
auth: {
'user': 'usr',
'pass': 'pwd'
},
json: true
};
return rp( options )
.then( body => {
// var test = JSON.stringify(body)
var doco =body.ServiceRequest1.subforms.z_DOCO_137.value;
console.log('DOCO '+doco);
resolve( doco );
})
.catch( err => {
console.log('FAILED'+err);
reject( err );
});
});
}
The error is thrown once i deploy the code in inline editor.The error is:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: TypeError: Cannot read property 'prototype' of undefined
at module.exports (/user_code/node_modules/request-promise-native/node_modules/request-promise-core/configure/request2.js:34:47)
at Object.<anonymous> (/user_code/node_modules/request-promise-native/lib/rp.js:15:1)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:17:23)
The request-promise-native package requires the request package as a co-dependency. So you need to explicitly add this to the package.json tab in the Dialogflow editor.
Here is the package.json that works for me:
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "~6.0"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "2.0.0-alpha.4",
"firebase-admin": "^4.2.1",
"firebase-functions": "^0.5.7",
"dialogflow": "^0.1.0",
"dialogflow-fulfillment": "0.3.0-beta.3",
"request-promise-native": "^1.0",
"request": "^2.87"
}
}
Don't forget that, in addition to having the correct package, you will need to upgrade the project to a paid account. The free Firebase "Spark" plan does not allow network access outside of Google's network. You can upgrade to the "Blaze" plan which is pay-as-you-go, but does have a free tier which is sufficient for most development and testing purposes.