Importing git npm modules results in undefined - javascript

I have made a npm module in a private git repo and I'm trying to access it in another application.
I'm using reactjs, webpack and npm
So I have the module:
dist
src
| form-mapper
| formMapper.js
| myfile.js
| index.js
package.json
webpack.config.js
Webpack.config.js is like this:
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js'
}
}
Package.json is like this:
{
"name": "my-awesome-module",
"version": "1.0.0",
"license": "ISC",
"main": "./dist/bundle.js",
"scripts": {
"prepare": "npm run build",
"build": "webpack --mode production",
"start": "webpack-dev-server --open --mode development"
},
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.0"
}
}
formMapper.js as 2 functions that I'm trying to export:
export function mapForm() {
// some code
}
export function mapUiFormToBackEnd() {
// some code
}
And index.js:
import * as FormMapper from './form-mapper/formMapper'
export { mapForm, mapUiFormToBackEnd } from './form-mapper/formMapper'
export default FormMapper
I've tried a lot of things in index.js so I let everything here just to show you guys what I've already tried.
In my app that needs to use this module I import the module using npm (git+ssh://...) which is working since I can see my module inside node_modules.
When I try to import using:
import FormMapper from 'my-awesome-module'
componentDidMount() {
FormMapper.mapForm()
}
I have this error:
my-awesome-module__WEBPACK_IMPORTED_MODULE_2___default.a.mapForm is not a function
That's my first time trying to create my own npm module and I clearly don't understand everything. I tried several guide but it seems I'm not abla to make it right.
Thanks for the help.
Edit:
When I log my import in my application
import FormMapper from 'my-awesome-module'
componentDidMount() {
console.log(FormMapper)
FormMapper.mapForm()
}
I see an empty object {} getting logged

update your formMapper.js in a more proper way
const mapForm = () => {
// Code here
}
const mapUiFormToBackEnd = () => {
// Code here
}
module.exports = {mapForm, mapUiFormToBackEnd }
on your index.js
// If you just want the mapForm and mapUiFormToBackEnd
const {mapForm, mapUiFormToBackEnd} = require('./form-mapper/formMapper');
// Or if you just want to get all it's fucntion just import it like this
const FormMapper = require('./form-mapper/formMapper') // No need for *
// export the whole FormMapper
module.exports = FormMapper;
// If you want to export a specific functions inside FormMapper
module.exports = {mapForm, mapUiFormToBackEnd }

Related

Why does Jest keep giving me error "SyntaxError: Cannot use import statement outside a module' "? I am using Babel to transpile ES6 for Jest to test

Why do I keep getting error message "SyntaxError: Cannot use import statement outside a module" when I use Babel and Jest?
I have a super simple app that contains two modules:
// moduleTwo.mjs:
let testFuncOneModTwo = () => {
return ('String generated by fn in moduleTwo.mjs')
}
export {testFuncOneModTwo }
/////////////
// moduleOne.mjs:
import {testFuncOneModTwo} from './moduleTwo.mjs'
let testFuncOneModOne = () => {
return (testFuncOneModTwo())
}
export { testFuncOneModOne }
//////////////
Here's my Jest test file:
// myTest.test.js:
import * as myImports from './moduleOne.mjs';
test('tests fn in module that calls fn in another module.', () => {
expect(myImports.testFuncOneModOne()).toEqual( 'String generated by fn in
moduleTwo.mjs' );
});
/////////////
// babel.config.json:
{
"presets": ["#babel/preset-env"]
}
// package.json:
{
"name": "JestIsVeryTesting",
"version": "1.0.0",
"description": "",
"main": "moduleOne.mjs",
"scripts": {
"test": "jest --coverage "
},
"jest": {
"transform": {
"^.+\\.js?$": "babel-jest"
}
},
"dependencies": {
"#babel/runtime": "^7.18.6"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.18.6",
"#babel/preset-env": "^7.18.6",
"babel": "^6.23.0",
"babel-jest": "^28.1.2",
"jest": "^28.1.2"
}
}
// The error message (edited by me):
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. ...
...
...
Details:
/xxx/xxx/xxx/xxx/moduleOne.mjs:91
import { testFuncOneModTwo } from './moduleTwo.mjs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
> 2 | import * as myImports from './moduleOne.mjs';
| ^
3 |
4 | test('tests fn in module that calls fn in another module.', () => {
5 | expect(myImports.testFuncOneModOne()).toEqual( 'This string returned by a function in moduleTwo.mjs' );
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (myTest.test.js:2:1)
Help would be much appreciated as this is driving me mad.
In case anyone is interested I solved the problem myself in the end:
To the top level of the package.json file I added:
"type": "module"
This tells node that all files in the project that end with '.js' are ES6 files
I changed the extensions of my modules to '.js'
(so that
'moduleOne.mjs' became 'moduleOne.js'
and
'moduleTwo.mjs' became 'moduleTwo.js'
)
This is in keeping with the value of the package.json file's "jest" field, which has value:
"transform": {
"^.+\\.js?$": "babel-jest"
}

Customize-cra config-overrides.js is not working

I am working on the create-react-app project with typescript. I am trying to use _ (lodash) globally. I followed manuals step by step trying to figure out how to do it, but without any success.
I followed this tutorial https://www.npmjs.com/package/customize-cra. My package.json contains between dependecies:
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"react-app-rewired": "^2.1.8",
"save-dev": "^0.0.1-security"
In devDependencies:
"customize-cra": "^1.0.0"
Based on tutorials I changed also scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",...
My config-overrides.js is located in root folder:
const { addDecoratorsLegacy, override, disableEsLint } = require('customize-cra')
const webpack = require('webpack')
function myOverrides(config) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ProvidePlugin({
_: 'lodash',
}),
)
return config
}
module.exports = override(
addDecoratorsLegacy(),
disableEsLint(),
myOverrides
)
I try to use join(['Hello', 'webpack'], ' ') but failed with error.
TypeScript error in C:/Users/.../webapp/src/index.tsx(27,1): Cannot find name 'join'. TS2304
Does anybody have any idea what should go wrong?
Thank you.

ECMAscript export in Node.js

Im creating an NFL football simulator in nodejs and am having trouble exporting one of my variables. As you can see in my get_teams.js i make many HTTP requests. I then process the responseArr and format the data. Where I am running into an issue is when I try and export the sorted_teams_array. you can find this code at the very bottom of get_teams.js.
I then try and import this array into tester.js and console log it. I will eventually use this file to inject a mongo database with the array, but for now am just trying to console log it and cannot get it to work. I am using the --experimental-modules in my npm scripts when I run npm run tester, and still nothing. Any help would be great! I am a noobie so please no hate!
get_teams.js
import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js';
import Defensive_stats from '../models/defensiveStatsModel.js';
import Game_stats from '../models/gameStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();
const teams = {};
function get_teams() {
axios.all([
axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/${process.env.SEASON}?key=${process.env.API_KEY}`),
// ... many more gets
])
.then(function (responseArr) {
responseArr[0].data.forEach(element => {
teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
element.PointsFor, element.PointsAgainst)
});
// many more forEach blocks on responseArr[1, 2, 3...]
/* power rating algorithm logic
_____________________________________________ */
const teams_array = Object.entries(teams);
export const sorted_teams_array = teams_array.sort((a, b) => {
if (a[1].average_victory_margin > b[1].average_victory_margin) return -1;
if (a[1].average_victory_margin < b[1].average_victory_margin) return 1;
return 0;
})
console.log(sorted_teams_array);
teams_array.forEach(element => {
console.log(`average victory margin for ${element[0]} = ${element[1].average_victory_margin}`)
});
})
.catch(function (error) {
// handle error
console.log(error);
})
}
get_teams();
tester.js
import { sorted_teams_array } from './get_teams';
console.log(sorted_teams_array);
/// returns
(node:58769) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module /Users/jojovera/Documents/nflSIMULATION/teams/get_teams imported from /Users/jojovera/Documents/nflSIMULATION/teams/tester.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:94:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
package.json
{
"name": "optionsscript",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node --experimental-modules app.js",
"afc_west": "node --experimental-modules ../nflSIMULATION/teams/afc_west.js",
"get_teams": "node --experimental-modules ../nflSIMULATION/teams/get_teams.js",
"tester": "node --experimental-modules ../nflSIMULATION/teams/tester.js",
"get_offensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_offensive_stats.js",
"get_defensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_defensive_stats.js",
"get_victory_margin": "node --experimental-modules ../nflSIMULATION/teams/get_victory_margin.js",
"power_rank": "node --experimental-modules ../nflSIMULATION/teams/power_rank.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.0",
"cheerio": "^1.0.0-rc.5",
"colors": "^1.4.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.6",
"stats-lite": "^2.2.0",
"terminal-kit": "^1.44.0",
"tofixed": "^1.0.0"
}
}
As addressed in the comments and chat, there were two issues: ESM isn't supported in Node 12, so an update to 15 fixed that. The other issue is that nothing was validly exported from get_teams: import and export are top-level keywords, and the export was taking place inside a .then. These minor changes allow the function to be imported and its result used in the tests:
export function get_teams() {
return axios.all([
/// rest of code
return sorted_teams_array;
})
.catch(function (error) {
// handle error
console.log(error);
})
}
Usage example:
import { get_teams } from './get_teams'
get_teams.then((teams) => {
teams.forEach(console.log)
})

Getting ParseError: Identifier is expected on importing svelte files for testing with jest

My Jest config details are
jest.config.js
module.exports = {
transform: {
'^.+\\.svelte$': 'svelte-jester',
'^.+\\.js$': 'babel-jest',
},
moduleFileExtensions: ['js', 'svelte'],
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
package.json
.
.
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"jest": "^26.0.1",
"svelte-jester": "^1.0.6",
"#testing-library/svelte": "^3.0.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack",
"dev": "webpack-dev-server --content-base public",
"test": "jest src",
"test:watch": "npm run test -- --watch"
},
.
.
I created src/test folder where my test.spec.js is as follows
import {fireEvent, render} from '#testing-library/svelte';
import App from '../App.svelte';
describe('test', () => {
test('Just a mock test', async () => {
const myMock = jest.fn();
console.log(myMock());
myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
});
});
Plz note that this I used a jest mock function just for testing purpose but whenever I import a svelte file as in this case App.svelte I get an error as below
FAIL src/test/test.spec.js
● Test suite failed to run
ParseError: Identifier is expected
I found a possible solution to this parsing error. Apparently, the IDE was unable to resolve certain style classes in the test.svelte file defined inside style tag, which is why it was showing up ParseError.
I would suggest anyone coming across this error to check your svelte file thoroughly for errors since svelte-testing-lib parses through the entire file before executing any test function.

How to import extension along with files in visual studio code?

Development using nodejs for running (--experimental-modules)
Current visual studio code intelligence import as below
import config from "./config";
but required as below
import config from "./config.js";
Without .js getting error as below
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module C:\Uday\Projects\practice-server\config imported from C:\Uday\Projects\practice-server\index.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:85:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
So i need visual studio code intelligence for importing with extension??
//index.js
import express from "express";
import config from "./config.js";
const api_app = express();
const api_port = config.api_port
api_app.listen(api_port, () => {
console.log(`Practice Server started on ${api_port}`);
});
//package.json
{
"name": "practice-server",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
//config.js
let config = function () { };
config.api_port = 6000;
export default config;
In the global settings (or the project settings), add the following configuration:
// Preferred path ending for auto imports.
// - auto: Use project settings to select a default.
// - minimal: Shorten `./component/index.js` to `./component`.
// - index: Shorten `./component/index.js` to `./component/index`
// - js: Do not shorten path endings; include the `.js` extension.
"javascript.preferences.importModuleSpecifierEnding": "js",
Note that at the moment this only works for auto imports (i.e via intellisense when referencing an export of another file and VSCode imports it automatically). It does not work with with autosuggest when typing the import statement manually.
I always used my config.js like this this. May be it can help you.
const config = require('./config');
//Now access value from config
const sys_dbconfig = config_data['sys_database'];
const user = configdata['system_admin_name'];
Here is my config.js
var config = {
"sys_database": {
"user": 'postgres',
"host": 'localhost',
"database": 'postgres',
"password": 'postgres',
"port": "5432"
},
"system_admin_name": "system",
"url":"http://xxx.xx.x.xxx:3000/wscalc1?wsdl"
}
module.exports = config;

Categories