How to use es6 import instead of require? - javascript

I want to use import in my file, but I cant find the way to replace my require properly
See the code I want to replace
const object = {
first: require('../example/first.json').EXL.PUBLIC,
second: require('../example/second.json').EXL.PUBLIC,
third: require('../example/third.json').EXL.PUBLIC
}
First question is how can I import those stuff directly to an object? Just like I did with require?
The second one, how can I use import with the .EXL.PUBLIC command? To directly import the right branch of the json file?

First question is how can I import those stuff directly to an object?
You can't, you have to import them and then add them to the objct.
The second one, how can I use import with the '.EXL.PUBLIC' command?
You have to import the item, then extract that property.
I'm going to assume you're using Node.js:
v8 through v11
In an .mjs module, you can do it like this:
import firstRoot from "../example/first.json";
import secondRoot from "../example/second.json";
import thirdRoot from "../example/third.json";
const object = {
first: firstRoot.EXL.PUBLIC,
second: secondRoot.EXL.PUBLIC,
third: thirdRoot.EXL.PUBLIC
};
v12
You can still do it as in v11.
If you use ESM with a .js file via the new "type": "module" in package.json, you need to add the --experimental-json-modules flag to enable JSON loading. More about v12's support here, but note that --type isn't yet supported (and if it is, will probably be --entry-type), and the JSON flag is --experimental-json-modules, not --experimental-json-loader).

Related

How i can fix js import auto-hide problem in vs code

Firstly, I imported something from another module in js:
import cloneDeep from './node_modules/lodash-es/cloneDeep.js'
But when I am not using this cloneDeep in my code and save my script file, then VS Code automatically hides that line.
Before Save
After Save
vcode settings.json
{
"editor.codeActionsOnSave": {
"source.organizeImports": false
},
}
try instead of import cloneDeep from './node_modules/lodash-es/cloneDeep.js
this: import cloneDeep from 'lodash-es/cloneDeep.js
you don't need to specify node_modules absolute path and if it's es6 import you need to add an entry in package.json:
"type": "module"
are you running it in NodeJs?
edit: if the code editor deleting it then it must be from a linter/extension causing it. Probably because you set the variable as global. either check the extension config or disable it or wrap the variable declaration in a function

Import dynamically named exports

Is it possible to import named exports dynamically?
I have a file, banana.js with hundreds of named exports. Id like to import them on demand. Is this possible? And if it is, will it only load that export and not all?
I know its possible to import them dynamically from individual files but I want them in the same file.
Example below..
// banana.js
export const banana_1 = {
..
}
export const banana_2 = {
..
}
// main.js
const currentPage = 1
async getSomething(){
let { `banana_${currentPage}` } = await import('./banana.js');
const foo = `banana_${currentPage}`
}
Fyi im using Vue.js
From what I know, you might have to use require('./banana.js') here. Please note that require is synchronous, so need for await. If you use eslint and it forbids usage of require, just add // eslint-disable-line to the end of that line. BTW, I don't know Vue at all.
About the object you import, you should probably make an array instead of suffixing each export with a number.
Edit: I just realized that dynamic imports are a thing not only possible with require, so ignore the first paragraph.
Based on your response to my question I offer the following solution. I understand not wanting to deploy and use a full database solution for the sake of hot loading some JSON objects. I'm unsure of your use case and other details related to your project.
You can use a self contained database like SQLite. Instead of setting up a NoSQL or SQL server. You can instead just store what you need to the SQLite file. Since Vue requires Node.js you can use the Node.js SQLite3 library https://www.npmjs.com/package/sqlite3.
I hope this helps.

How to publish a library to npm that can be used both with import and require?

tealium-tracker is written in es6 and transpiled using Babel before published to npm.
When consumers do:
import initTealiumTracker from "tealium-tracker";
everything works as expected.
However, some consumers want to use a require instead of an import, and have to append .default:
const initTealiumTracker = require("tealium-tracker).default;
How could I publish the library to avoid appending .default?
I want consumers to be able to do either:
import initTealiumTracker from "tealium-tracker";
or
const initTealiumTracker = require("tealium-tracker);
Source code
In your source code, If you are ok with using commonJS syntax for import and export...
One option would be to replace all import and export with require and module.exports. Looks like webpack doesn't allow mixing the syntaxes (ES6 and commonJS modules).
So your index.js file can require the functions from dependent module as
const { callUtag, flushUtagQueue } = require("./utagCaller");
and export the default function as
module.exports = initTealiumTracker;
module.exports.default = initTealiumTracker;
Likewise your dependent module can export the functions as
module.exports = { callUtag, flushUtagQueue };
This way, consumers should be able to use either
import initTealiumTracker2 from "tealium-tracker";
OR
const initTealiumTracker1 = require("tealium-tracker");

Importing from validator in javascript

I want to use the validator for an express project. How do I import just two subsets of the packages directly?
Like:
import {isEmail, isEmpty} from 'validator';
or importing each on a separate line.
I just want to know if there is another option apart from import validator from 'validator'; as stated on the https://www.npmjs.com/package/validator
const isEmailValidator = require('validator').isEmail;
const isEmptyValidator = require('validator').isEmpty;
isEmailValidator('bla#bla.com');
Like this you mean? What you wrote should also be valid:
import {isEmail, isEmpty} from 'validator';
isEmail('bla#bla.com');
Edit for clarification: As you can see here https://github.com/chriso/validator.js/blob/master/src/index.js the library is exporting an object with each function. You can import everything import validator from 'validator' or you can use destructuring to get only a few properties.
const {isEmail, isEmpty} = require('validator');
This will not actually stop node from importing all of validator though. This just has node load the validator object that is returned from that modules export and then destructures isEmail and isEmpty out of the exported Object.
Maybe whenever ES6 modules become full supported you can use the regular import syntax. See node.js documentation: ECMAScript Modules.

Javascript JSX, illegal import declaration

I have a jsx file using React components with Reflux. There is only one tiny action:
var ClickedAction = Reflux.createActions([
'clicked'
]);
How can I move this action to another file? According to the JSX documentation, it should be easy to include other files:
// import all classes that do not start with "_" from "a.jsx"
import "a.jsx";
I tried to move it in actions/clickedAction.jsx (or .js) and import it using import "actions/clickedActions.jsx" but I keep getting Illegal import declaration. How can I achieve this?
I am not using RequireJS and would like to avoid it if possible. One alternative solution I have found is to include this in the HTML file,
<script type='text/javascript' src='xxxxx/actions/clickedAction.js")'></script>
, but this is not ideal and would like to find another way. Thanks for your attention and help.
If you use Babel:
export default ClickedAction; // in action file
Otherwise, use old modules:
module.exports = ClickedAction; // in action file
require('actions/clickedActions.jsx'); // in another file

Categories

Resources