How to export and use the ECMA6 class? This is what I am doing now:
parser.js
module.exports = class Parser {
static parse() {
}
static doNow() {
}
}
Now in another file, I am doing:
var Parser = require('parser')
Parser.parse();
When parse is called on Parser, I get an error saying
SyntaxError: Unexpected identifier
with Parser highlighted.
What could be the reason for this? What is the correct to export and import the class?
You try to call your module in an absolute way this is what causes problem.
I recommend using an IDE as webstorm or atom to not have this kind of problem in the future
try this :
var Parser = require('path/path/parser.js');
Parser.parse();
for es6 is :
export default class Parser {
static parse() {
}
static doNow() {
}
}
import Parser from './path/path/parser';
It's easier and more readable to do it like this:
class Parser {
static parse() {
}
static doNow() {
}
}
module.exports = Parser;
and in the requiring module:
const Parser = require('./path/to/module');
Parser.doNow();
// etc.
I tested this and it seems the issue is the path of parser.
File Structor
-index.js
-parser.js
index.js
var Parser = require('./parser')
console.log('parser',Parser.parse());
parser.js
module.exports = class Parser {
static parse() {
return 'hello there'
}
static doNow() {
}
}
Terminal
node index.js
parser hello there
Related
How to include functions in namespace / module when don't have module?
example: I have a namespace:
namespace Java {}
in typescript, usually when we need a function in namespace or module, we add 'export':
namespace Java {
export function version() {
return "java8";
}
}
namespace JavaScript {
function JavaVer() {
return Java.version();
}
}
But if I set module to none:
// tsconfig
"module": "none",
If module is none, I cannot use import / export:
website/sourcecode/main.ts:17:21 - error TS1148: Cannot use imports, exports, or module augmentations when '--module' is 'none'.
17 export function version() {}
so what can I do?
image:
You can use a plain object:
TS Playground
const Java = {
version () {
return "java8";
},
};
const JavaScript = {
JavaVer () {
return Java.version();
},
};
const vJ = Java.version(); // string
const vJS = JavaScript.JavaVer(); // string
console.log(vJ === vJS); // true
It was answered in here: It's actually "can't have any imports or exports at the top level". Imports and exports inside namespaces are fine because they don't export anything from .ts file at runtime, and as long as file remains 'not a module' module=None works fine. Long explanation here
I'm trying to use the ES6 import syntax and keep running into errors.
This is my data type,
class UnionFind{
constructor(n){
this.items = n;
}
union(p, q){
}
connected(p, q){
}
find(p){
}
count(){
}
}
export default UnionFind
Saved in a file UnionFind.js
This the calling client,
import { UnionFind } from './unionFind';
const readline = require('readline');
const rl = readline.createInterface({
input:process.stdin,
output:process.stdout,
terminal:false
});
uf = new UnionFind(10)
rl.on('numbers', function (line) {
arr = number.split(' ')
console.log(arr);
});
This is saved in a file client.mjs
This is how I'm running it,
node --experimental-modules union-find/client.mjs
I get the following error,
(node:13465) ExperimentalWarning: The ESM module loader is experimental.
file:///Users/mstewart/Dropbox/data-structures-algorithms-princeton/union-find/client.mjs:1
import { UnionFind } from './unionFind';
^^^^^^^^^
SyntaxError: The requested module does not provide an export named 'UnionFind'
at ModuleJob._instantiate (internal/modules/esm/ModuleJob.js:89:21)
at <anonymous>
What am I doing wrong here?
In this case, use
import UnionFind from './UnionFind.js';
if you declared
export class UnionFind{ ....
then you use
import { UnionFind } from './UnionFind.js';
Also take a look at the file name: UnionFind.js . You are using './unionFind'. This is case sensitive
I am exporting a function like this which works.
module.exports = function (options: any): RequestHandler {
// Do stuff
}
I am trying to add a definition for the exported function, but I am not sure if this is the right way to do it:
declare global {
export function tsm(options: any): RequestHandler
}
When I try to test it both of the following say that this is valid:
const tsm = require('ts-middleware')
global.tsm() // Gives intellisense
tsm() // Also gives intellisense
It shouldn't give information about global.tsm(), so I think that I created my definition wrong. What is the correct way to create a function definition?
I don't want to use the function like this:
const tsm = require('ts-middleware')
tsm.tsm()
But I do want to use it like this:
const tsm = require('ts-middleware')
tsm()
To define typings for a module, use declare module 'x' {...}. i.e.:
declare module 'ts-middleware' {
export = (option: any): RequestHandler
}
However, you do not really need to do that because you wrote your code in TypeScript. The compiler can generate the typings for you automatically.
You just need to add declaration: true in your tsconfig.json:
// tsconfig.json
{
"compilerOptions": {
"declaration": true
}
}
Also, I would strongly recommend you to write your code using ESM. i.e. instead of module.exports = ...:
// named export, preferred
export function foo(options: any): RequestHandler { ... }
// or default export
export default function foo(options: any): RequestHandler { ... }
// import in TypeScript for named export
import { foo } from 'ts-middleware'
// import in TypeScript for default export
import foo from 'ts-middleware'
// require in JavaScript commonjs
const middleware = require('ts-middleware')
middleware.foo(...)
With the use of ES6 Module Loader Polyfill, I've found that given a JavaScript file (module1.js):
export class q {
constructor() {
console.log('this is an es6 class!');
}
}
One can import the mentioned module with the following code:
<script>
System.import('mymodule').then(function(m) {
new m.q();
});
</script>
My question is: I need to do this (almost) very same thing but instead of importing a file, use a String literal. For example:
<script>
module = `
export class q {
constructor() {
console.log('this is an es6 class!');
}
}
`;
System.import(module).then(function(m) { // not possible
new m.q();
});
</script>
The reason of this, is because the Angular app receives the module as a response from a HttpRequest call embedded in a Json response like this:
{
"module": "export class q {
constructor() {
console.log('this is an es6 class!');
}
}"
}
I am looking to create a Modules system within my Application. I'm unsure on how to implement the following:
Module 1
class SomethingModule {
}
export default SomethingModule;
Module 2
class SomethingElseModule {
}
export default SomethingElseModule;
Module Loader
class ModuleLoader {
load(module) {
// "module" could be "Something" which should create a
// new instance of "SomethingModule"
module = module + 'Module';
// Require and create an instance of "module"
}
}
export default ModuleLoader;
Main File
var ModuleLoader = require('./ModuleLoader');
var loader = new ModuleLoader();
loader.load('SomethingElse');
I'm pretty new to modularised JavaScript and have no idea if this is even possible/feasible. If not, is there a way of doing this you'd suggest without polluting the global namespace and referencing window[moduleName]?
If I understand well your problem, you can create a Map and load your module in there:
class ModuleLoader {
constructor() {
this._modules = new Map();
}
load(module) {
// you should check if the module exist in a good world to not get any error
// and probably adjust the path of what you are requiring
this._modules.set(module, new require(`${module}Module`));
}
getModuleByName(name) {
return this._modules.get(name);
}
}
Edit: To make it work with browserify, you will need to have this list of all the modules somewhere. You can create a separate file ModuleBag like this:
//moduleBag.js
import yourModule from './yourModule';
import yourSecondModule from './yourSecondModule';
var map = new Map();
map.set('yourModule', yourModule);
map.set('yourSecondModule', yourSecondModule);
export default class map;
//moduleLoader.js
import moduleBag from './moduleBag';
class ModuleLoader {
constructor() {
this._modules = new Map();
}
load(module) {
var mod = moduleBag.get(module);
this._modules.set(module, new mod());
}
getModuleByName(name) {
return this._modules.get(name);
}
}
or just put it in the same file.
With this, browserify will be able to load all the necessary files.