Both Require and import not working javascript - javascript

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.

Related

Jest issue when I run the test cases via the command

I am newbie on Jest and I have the following issue when I execute the command
npm test
I have the following files
functions.js
const functions = {
add: (num1,num2) => num1 + num2
};
module.exports = functions;
and the functions.test.js
const functions = require('./functions');
test(`Adds 2 + 2 to equal 4`, ()=>{
expect(functions.add(2,2)).toBe(4);
});
my package.json has the following context
{
"name": "jest-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.2.2"
}
}
I havent found a lot of resources on the internet regarding the error I just try to remove the dot (.) character from the node_modules/jest
and the output of the console (error) is below
> jest-tutorial#1.0.0 test
> jest
C:\Users\agiallelis\node_modules\jest-cli\build\run.js:129
if (error?.stack) {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:1054:16)
at Module._compile (internal/modules/cjs/loader.js:1102:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (C:\Users\agiallelis\node_modules\jest-cli\build\index.js:12:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)

GraphQL - problem with the code from the tutorial page, it pops up an error "Expected undefined to be a GraphQL schema."

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.

node js MODULE_NOT_FOUND error in node_modules

I am new to javascript and I am having import issues.
I have installed the jquery.csv lib as npm i jquery.csv but then node is not able to import it. (this was the procedure described in https://github.com/typeiii/jquery-csv)
Here is the structure of my project:
lucapuggini#lucas-MBP js_utils % ls
index.js index.js~ node_modules package-lock.json package.json
lucapuggini#lucas-MBP js_utils % ls node_modules
jquery-csv
lucapuggini#lucas-MBP js_utils % cat index.js
var csv = require('./jquery.csv.js');
console.log("Start index.js")
lucapuggini#lucas-MBP js_utils % cat package-lock.json
{
"name": "js_utils",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"jquery-csv": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/jquery-csv/-/jquery-csv-1.0.11.tgz",
"integrity": "sha512-KDPc3wFLTFO68p/4IqsODZCjBp+y9axDa/pr36pDKrWk6yyHf8Nk1FqAGXvaUb6H7J1zJSYszABIFj0a40QXRA=="
}
}
}
lucapuggini#lucas-MBP js_utils % node index.js
node:internal/modules/cjs/loader:922
throw err;
^
Error: Cannot find module './jquery.csv.js'
Require stack:
- /Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:15)
at Function.Module._load (node:internal/modules/cjs/loader:763:27)
at Module.require (node:internal/modules/cjs/loader:991:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js:2:11)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/lucapuggini/ProgrammingProjects/padel/trunk/js_utils/index.js'
]
}
lucapuggini#lucas-MBP js_utils %
Why am I getting this error?
It seems their documentation is incorrect. You need to require the npm module like this:
const csv = require('jquery-csv');

How to use ospec with mithril javascript

I'm trying to use o.spec to test mycomponent but failed.
The error message of "dart test" is:
tests/MyComponent.js:1
(function (exports, require, module, __filename, __dirname) { import MyComponent from "./src/mycomponent"
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Glob.<anonymous> (node_modules/mithril/ospec/bin/ospec:37:37)
error Command failed with exit code 1.
setup by npm or yarn:
yarn add mithril#next webpack webpack-cli
edit package.json:
{
...
"name": "my-project",
"scripts": {
"start": "webpack src/index.js --output bin/app.js -d --watch",
"build": "webpack src/index.js --output bin/app.js -p",
"test": "ospec"
}
}
index.html:
<!DOCTYPE html>
<body>
<script src="bin/app.js"></script>
</body>
src/mycomponent.js:
//var m = require("mithril")
import m from "mithril"
//module.exports = {
export default {
view: function(vnode) {
return m("div",
m("p", "Hello World")
)
}
}
src/index.js:
import m from "mithril"
import MyComponent from "./mycomponent"
//var m = require("mithril")
//var MyComponent = require("./mycomponent")
m.mount(document.body, MyComponent)
tests/MyComponent.js
import MyComponent from "./src/mycomponent"
//var MyComponent = require("./src/mycomponent")
o.spec("MyComponent", function() {
o("returns a div", function() {
var vnode = MyComponent.view()
o(vnode.tag).equals("div")
o(vnode.children.length).equals(1)
o(vnode.children[0].tag).equals("p")
o(vnode.children[0].children).equals("Hello world")
})
})
You need to mock the environment using
global.window = require("mithril/test-utils/browserMock.js")();
global.document = window.document;
in your tests.
Check more at https://mithril.js.org/testing.html

Webpack Dynamic Config Loading Fails

I was following instructions to import config dynamically based on an environment variable using webpack. This is according to official documentation:
https://webpack.js.org/plugins/normal-module-replacement-plugin/
Example:
File: package.json
{
"name": "03_branching",
"version": "1.0.0",
"description": "",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"develop": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"dependencies": {
"string-replace-loader": "^2.1.1",
"webpack": "~4.6.0"
},
"devDependencies": {
"webpack-cli": "^2.0.15"
}
}
Example:
File: configLoader.js
const fs = require('fs');
console.log('fs', fs);
const config = fs.readFileSync("./config/APP_ENV.json");
const properties = JSON.parse(config);
console.log("Environment: " + properties.environment);
console.log("HomepageUrl: " + properties.homepageUrl);
File: webpack.config.js
"use strict";
const webpack = require('webpack');
const path = require('path');
module.exports = function(env) {
console.log('NODE_ENV: ', env.NODE_ENV); // 'local'
let newEnv = 'local';
if (env.NODE_ENV !== undefined) {
newEnv = env.NODE_ENV;
}
console.log('newEnv', newEnv);
return {
target: 'web',
node: {
fs: 'empty'
},
entry: path.join(__dirname, "./", "configLoader.js"),
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
rules: [
{
test: /configLoader\.js$/,
loader: 'string-replace-loader',
options: {
search: 'APP_ENV',
replace: `${newEnv}`,
flags: 'i'
}
}
]
}
}
};
File: config/local.json
{
"environment": "local",
"homepageUrl": "http://localhost:8080"
}
File: config/production.json
{
"environment": "production",
"homepageUrl": "http://www.google.com"
}
I try and run node dist/bundle.js but I get the following error...
➜ 03_branching git:(master) ✗ node dist/bundle.js fs {} /Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1
(function (exports, require, module, __filename, __dirname) { var EntryPoint=function(n){var e={};function o(r){if(e[r])return e[r].exports;var t=e[r]={i:r,l:!1,exports:{}};return n[r].call(t.exports,t,t.exports,o),t.l=!0,t.exports}return o.m=n,o.c=e,o.d=function(n,e,r){o.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:r})},o.r=function(n){Object.defineProperty(n,"__esModule",{value:!0})},o.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return o.d(e,"a",e),e},o.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},o.p="",o(o.s=1)}([function(n,e){},function(n,e,o){const r=o(0);console.log("fs",r);const t=r.readFileSync("./config/production.json"),c=JSON.parse(t);console.log("Environment: "+c.environment),console.log("HomepageUrl: "+c.homepageUrl)}]);
TypeError: r.readFileSync is not a function
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:686)
at o (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:186)
at /Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:600
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:609)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
It works if I run
node configLoader.js
But if I run the webpack command:
webpack --env.NODE_ENV=production
node dist/bundle.js
It fails... How do you bundle all of the node core modules here using webpack? I'm using webpack version 4.6.0
Cheers!
You are using the wrong target.
readFileSync only exists in node. But you are compiling for web.
If you change your target to node, everything should work.
I suspect you don't want to load the config file on runtime, but compile different option depending on the environment?
If so, take a look at webpack-define-plugin. You can put your config in a variable without loading a file on runtime.
This will then also work in the browser.

Categories