I must be missing some very basic here about importing an external package function to my plain javascript project / file.
I have a simple project that I have started with npm init And then installed the normalizr package. I have to run the below kind of normalization code, and this is perfectly working when I run the below code inside a React Component.
But the import statement itself is failing in my simple plain JavaScript file/project.
const normalize = "./node_modules/normalizr/dist/normalizr.js";
const schema = "./node_modules/normalizr/dist/normalizr.js";
const articlesData = {
articles: [
{
id: 1,
title: "Dagon",
tags: [{ id: 1, name: "old ones" }, { id: 2, name: "short story" }]
},
{
id: 2,
title: "Azathoth",
tags: [{ id: 1, name: "old ones" }, { id: 3, name: "novel" }]
},
{
id: 3,
title: "At the Mountains of Madness",
tags: [{ id: 4, name: "insanity" }, { id: 3, name: "novel" }]
}
]
};
const tag = new schema.Entity("tags", {});
const article = new schema.Entity("articles", {
tags: [tag]
});
// We assume articlesData is the (parsed) JSON object that we got
const normalizedData = normalize(articlesData, { articles: [article] });
console.log(articlesData);
I have also tried to import the 2 functions (normalize, schema) as below which did not work
const normalize = require("normalizr");
const schema = require("normalizr");
And also tried the below way to run the file, which also failed
node --experimental-modules ./file.js
Had gone through this official page but which was not much help for me.
The below is my package.json file
{
"name": "test-js-codes-repo",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"babel": {
"presets": [
"@babel/preset-env"
]
},
"license": "ISC",
"dependencies": {
"@babel/cli": "^7.8.4",
"@babel/node": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"axios": "^0.19.2",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.0.6",
"babel-plugin-dynamic-import-webpack": "^1.1.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.26.0",
"es6-promise": "^4.2.5",
"esm": "^3.2.25",
"https": "^1.0.0",
"isomorphic-fetch": "^2.2.1",
"lodash.flatten": "^4.4.0",
"lodash.map": "^4.6.0",
"lodash.omit": "^4.5.0",
"lodash.orderby": "^4.6.0",
"lodash.partialright": "^4.2.1",
"lodash.pick": "^4.4.0",
"lodash.sortby": "^4.7.0",
"moment": "^2.22.2",
"normalizr": "^3.6.0",
"request": "^2.88.0"
},
"description": "",
"devDependencies": {
"babel-plugin-dynamic-import-node": "^2.3.0"
}
}
Import it like you would any other module import in Node.js require docs
const { normalize, schema } = require('normalizr')