I am trying to learn local module setup in my express js application.
test-module folder is created in my project folder and it contains two files
1)index.js
module.exports = {
indexfunc:function(){
console.log('ok from index');
}
}
2)hello.js.
module.exports = {
helloFunc:function(){
console.log('ok from hello');
}
}
importing this module in app.js file
var mymodule = require('hello-module');
console.log(mymodule);
output:{ indexfunc: [Function: indexfunc] }
But this returns console.log(require('hello-module').hello) undefined.
package.json for this module
{
"name": "hello-module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Since hello is a file in hello-module, you need to pass it as the path to require. Do:
console.log(require('hello-module/hello'))
By doing :
console.log(require('hello-module').hello)
You are printing the hello property exported by index.js
I addition to #Ayush answer, if your goal is to execute code from other files in a module folder you can export a reference like so :
//index.js
const helloModule = require('./hello');
module.exports = {
hello: helloModule,
indexfunc:function(){
console.log('ok from index');
}
}
Related
I have initiated a new project with NPM :
npm init
I have installed the socket.io-client package.
package.json:
{ "name": "client", "version": "1.0.0", "description": "", "main": "script.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "socket.io-client": "^4.5.4" } }
script.js:
import { io } from "socket.io-client";
const socket = io('http://localhost:3000')
socket.on('connect', () => {
console.log('Hello - ' + socket.id)
})
The error I get:
npm ERR! Missing script: "start"
I have added the start command to package.json:
"start": "node script.js"
Now I get:
SyntaxError: Cannot use import statement outside a module
I have tried adding start command, and did not worked.
You can try one of these:
Add type="module" to whereever you import your script.
Add "type": "module" to your package.json file.
See more here: "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
I'm relatively new to node.js and am attempting to utilize a javascript library without any success.
The library itself is psn-api.
To set up for usage I have:
Installed node.js locally
Created my project folder
Ran npm init and successfully created package.json
Ran npm install i -s psn-api which has successfully installed psn-api to my project folder in node-modules and updated the dependencies in package.json.
I've copied the sample code from the psn-api github (see below) and saved as index.ts file in my project folder.
I run npx tsc --init which generates my tsconfig.json file
I run npx tsc index.ts which compiles into index.js
I run node index.js
Sample code (index.ts):
import * as fs from "fs";
import type { Trophy } from "psn-api";
import {
exchangeCodeForAccessToken,
exchangeNpssoForCode,
getTitleTrophies,
getUserTitles,
getUserTrophiesEarnedForTitle,
makeUniversalSearch,
TrophyRarity
} from "psn-api";
async function main() {
// 1. Authenticate and become authorized with PSN.
// See the Authenticating Manually docs for how to get your NPSSO.
const npsso = "xxxxxxxx";
const accessCode = await exchangeNpssoForCode(npsso);
const authorization = await exchangeCodeForAccessToken(accessCode);
// 2. Get the user's `accountId` from the username.
const allAccountsSearchResults = await makeUniversalSearch(
authorization,
"xelnia",
"SocialAllAccounts"
);
const targetAccountId =
allAccountsSearchResults.domainResponses[0].results[0].socialMetadata
.accountId;
// 3. Get the user's list of titles (games).
const { trophyTitles } = await getUserTitles(authorization, targetAccountId);
const games: any[] = [];
for (const title of trophyTitles) {
// 4. Get the list of trophies for each of the user's titles.
const { trophies: titleTrophies } = await getTitleTrophies(
authorization,
title.npCommunicationId,
"all",
{
npServiceName:
title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
}
);
// 5. Get the list of _earned_ trophies for each of the user's titles.
const { trophies: earnedTrophies } = await getUserTrophiesEarnedForTitle(
authorization,
targetAccountId,
title.npCommunicationId,
"all",
{
npServiceName:
title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
}
);
// 6. Merge the two trophy lists.
const mergedTrophies = mergeTrophyLists(titleTrophies, earnedTrophies);
games.push({
gameName: title.trophyTitleName,
platform: title.trophyTitlePlatform,
trophyTypeCounts: title.definedTrophies,
earnedCounts: title.earnedTrophies,
trophyList: mergedTrophies
});
}
// 7. Write to a JSON file.
fs.writeFileSync("./games.json", JSON.stringify(games));
}
const mergeTrophyLists = (
titleTrophies: Trophy[],
earnedTrophies: Trophy[]
) => {
const mergedTrophies: any[] = [];
for (const earnedTrophy of earnedTrophies) {
const foundTitleTrophy = titleTrophies.find(
(t) => t.trophyId === earnedTrophy.trophyId
);
mergedTrophies.push(
normalizeTrophy({ ...earnedTrophy, ...foundTitleTrophy })
);
}
return mergedTrophies;
};
const normalizeTrophy = (trophy: Trophy) => {
return {
isEarned: trophy.earned ?? false,
earnedOn: trophy.earned ? trophy.earnedDateTime : "unearned",
type: trophy.trophyType,
rarity: rarityMap[trophy.trophyRare ?? 0],
earnedRate: Number(trophy.trophyEarnedRate),
trophyName: trophy.trophyName,
groupId: trophy.trophyGroupId
};
};
const rarityMap: Record<TrophyRarity, string> = {
[TrophyRarity.VeryRare]: "Very Rare",
[TrophyRarity.UltraRare]: "Ultra Rare",
[TrophyRarity.Rare]: "Rare",
[TrophyRarity.Common]: "Common"
};
I've run around in circles with possible fixes such as adding "type":"module" to the package.json, trying to import or otherwise define psn-api in my js file but I keep hitting error after error. I'm sure there's some fundamental misunderstanding I have. I'd really appreciate if someone could outline the direct steps I need to take to get the sample script running in the cmd line.
My package.json as it stands:
{
"name": "psnapitest",
"version": "1.0.0",
"description": "",
"main": "index3.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/node": "^18.6.2",
"psn-api": "^2.7.0"
},
"type": "module",
"devDependencies": {
"#tsconfig/node16": "^1.0.3",
"typescript": "^4.7.4"
}
}
My tsconfig.json as it stands (after advice in comments):
{
"compilerOptions": {
"target": "es2016",
"module": "es6",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
Current error when running compiled js:
Now compiles with no issues.
I run node index.js and get the following error
exports.__esModule = true;
^
ReferenceError: exports is not defined in ES module scope
I tried this locally and no error
when using node library you need to set "moduleResolution": "node" on your tsconfig.json
index.ts
import fs from 'fs'
package.json
{
"name": "psn-api-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc index.ts",
"start": "node index.js"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"psn-api": "^2.7.0"
},
"devDependencies": {
"#types/node": "^18.6.2",
"typescript": "^4.7.4"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "es6",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
Try instead of using import, use require:
const fs = require('fs')
const psn = require('psn-api')
type { Trophy } = psn
const { exchangeCodeForAccessToken } = psn
const { exchangeNpssoForCode } = psn
const { getTitleTrophies } = psn
const { getUserTitles } = psn
const { getUserTrophiesEarnedForTitle } = psn
const { makeUniversalSearch } = psn
const { TrophyRarity } = psn
Also, instead of compiling it to node.js, try using this library:
https://www.npmjs.com/package/ts-node
Its basicly node.js but for typescript
I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.
What do I need to change to get import to work?
I have 3 simple files in the same directory.
package.json
main.js
Utility.js
package.json
{
"name": "node_template",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Utility.js
'use strict';
class Utility {
constructor() {
}
}
export { Utility };
main.js
"use strict";
(async ()=>{
import { Utility } from './Utility.js';
var utility = new Utility();
console.log( "Main" );
})();
When I run "node main.js" I get the following error:
node -v
v16.0.0
node main.js
main.js:4
import { Utility } from './Utility.js';
^
SyntaxError: Unexpected token '{'
←[90m at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m at async link (node:internal/modules/esm/module_job:64:21)←[39m
main.js
(async () => {
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();
Note:
The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.
Links:
https://v8.dev/features/dynamic-import
https://flaviocopes.com/javascript-dynamic-imports/
I want simply import a function from an another file and I'm getting this error message:
SyntaxError: Cannot use import statement outside a module
I'm not using any html file. I'm using only js files with webpack that returns the result on the console with yarn start
Here is the code of the file that contains the function I want to export:
export function assert(value, desc) {
return value ? console.log(desc) : console.log('fail')
}
Here is the code of the file that I want to import the function:
import {assert} from './assert.js'
function juggle() {
var result = 0;
for(var n=0; n < arguments.length; n++) {
result += arguments[n]
}
this.result = result
}
var ninja1 = {}
var ninja2 = {}
juggle.apply(ninja1, [1,2,3,4])
juggle.call(ninja2, 5,6,7,8)
assert(ninja1.result === 10, "juggled via apply")
assert(ninja2.result === 26, "juggled via call")
Here is my package.json:
I don't know if it is userful to solve this issue, but here is, if you want to see it.
{
"name": "c",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "node Cap_03/01_apply_e_call.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack-dev-server": "^3.9.0"
},
"type": "module",
"devDependencies": {
"webpack": "^4.41.2"
},
"description": ""
}
As of Node 13.2.0+
Verify that you have the latest version of Node installed. Simply do one of the following:
Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
OR
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If you use an older Node version or have to
import statements are permitted only in ES modules.
For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to
add "type": "module" to package.json
add "--experimental-modules" flag to the node call
my webpack doesn't generate file though no errors shown. PLS help :D
i'm new to all this so dont be harsh pls :D
code in webpack.config.js
module.exports = {
entry : ['./app/index.js'],
output : {
path : '/build',
filename: 'bundle.js'
}
}
using npm run build, no errors returned.
package.json
{
"name": "es6",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"webpack": "^3.10.0"
},
"description": ""
}
After making a fresh directory, copying in your code as is, I get the following:
Error: EACCES: permission denied, mkdir '/build'
at Error (native)
It's trying to access the root level /build directory (which doesn't exist, at least for me).
Tweaking the config a bit more leads to this:
const path = require('path')
module.exports = {
entry : ['./app/index.js'],
output : {
// Get the path including the current directory node is running in
path : path.resolve(__dirname, './build'),
filename: 'bundle.js'
}
}
Which spits out a successful bundle.
There were no errors? Any output at all?