I'm having the following error in the console when I try to run my api written in node js.
Can you tell me which is the problem.
Importing is generally done at the top of your files and looks like this:
import User, {schema} from './model.js'
Exporting is generally done at the bottom of your files and looks like this:
module.exports = {User, schema}
Ant the specific reason why you get the error is because export is not used that way.
Here is a direct quote from Web Docs:
export DefaultExport from 'bar.js'; // Invalid
You are using ES6 syntax.
Node.js uses common.js syntax
You can use module.export syntax or you can use babel npm package for translate ES6 syntax to common.js syntax
If you want to include a structure you have built, you need to use import.
If you want to export a structure that you have edited, you need to use export.
Related
So I have two files: a.ts and b.ts. b exports something for a to use. The TypeScript compiler handles this fine, but refuses to create valid output for a browser. Example:
import { test } from "./b";
console.log(test);
b.ts
export const test = "quest";
and now I try compiling it:
$ tsc --lib dom,es2018 --target ES2018 --out test.js a.ts b.ts
b.ts:1:1 - error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
1 export const test = "quest";
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.
hm, weird. Okay, let's try using --module. If I use amd a browser that loads test.js will tell me: ReferenceError: define is not defined. If I try system it says: ReferenceError: System is not defined.
Okay, that's not working. Let's try without setting a single output file with --out. That gives me:
SyntaxError: import declarations may only appear at top level of a module a.js:1
SyntaxError: export declarations may only appear at top level of a module b.js:1
So based on this, it seems like my only options for using typescript are:
Put all code in a single file
Use an external library like require.js or webpack
Learn what a module is and if/how it can be used in a browser
Or am I missing something? How do I compile Typescript using imports without adding libraries/modules ?
TypeScript version: 3.8.3
Syntax error
please correct this
export const test = "quest";
to
export test = "quest";
No need to add any const here while exporting
I have a typescript file in which some functions have been added.
The following shows the actual address of the typescript file :
../myproject/src/util/validation/user-validation
All the functions are exported from the file. For instance,
export function validateSignUpData(userDetail:UserDetail):Array<String>{
let errorMessages = new Array<String>();
/* Some Code */
Now I am trying to use the exported function in Node server, though it throws an error which I do not comprehend.
Error: Cannot find module '../myproject/src/util/validation/user-validation'
This is how I tried to get the functions inside my Node server file:
app.post('/users',(req,res)=>{
let validator = require('../myproject/src/util/validation/user-validation');
let errorMessages = validator.validateSignUpData(req.body);
I googled require function, and it seemed that my code must work properly. Some forums suggests that typescript must be installed to resolve the issue, though I have already installed typescript!
I will be glad, if you help me!
Thank you.
The export keyword is used for ES6 modules (Related article also covering node.js). This is a new language feature that was shipped in 2015.
It uses export function name() {...} to export a function and import {name} from './path/to/file'; to import it somewhere else.
Node uses the CommonJs syntax (which is still largely popular).
The idea behind it is that any module (i.e. js-file) can export an object like this: module.exports = {key: "value"}. This object can then be imported using require('./path/to/file').
You can use es6 modules in node like this: How can I use an es6 import in node?.
There are 2 methods of modules in node js, es6 modules and requrejs
require is used together with module.exports
add this to your module
module.exports.validateSignUpData=validateSignUpData
and then the require function will export it.
The other way is to use es6 modules but it doesn't work under all circumstances
https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling
Hi i'm currently learning nodejs and I try to import a json file like this :
'use strict'
import data from 'users.json'
console.log(data)
Each time I get this error "Cannot find package 'users.json'"
But if I read the file with fs it worked so can you explain me how to do please
try :
import data from './users'
which is the es6 method of doing things or if you want an older syntax method you can try
const data = require('./users')
Okay so the explanation just is this, those fullstops and forward slash are used to indicate relative paths to the file the import is being called from, which means somethings you'd see something like for example ../file/help. The ./ means go up one directory ../ means go up two directories and so on. The name after the slash just tells your program the folder to go in to look for the file to import from so ./folder means go up one directory and enter into the folder directory and so on.
Almost forgot to mention, you should not import from a json file or a text file or any other file that does not have a .js extention(of which you do not actually have to specify) unless absolutely neccessary. To deal with files in node you have to use the fs library.
const fs =require('fs')
....
fs.readFile('./users.json','utf-8',(err,jsonString)=>{
const data = JSON.parse(jsonString);
//whatever other code you may fanacy
}
take a look at the fs module for a list of awesome features you can use to play with files
While the selected answer is correct, here's an explanation that I hope might add some clarity:
import MyModule from 'some-module'
is ES6 import syntax, as opposed to the older CommonJS syntax, which uses require.
CommonJS's require can be used to import files generally; ES6's import statement is more specific, and is generally used for importing js files which meet the criteria for being a module (having an export statement), or specific assets such as CSS sheets. Unlike require, it won't generally work for reading in files that are not modules.
You can't mix CommonJS require and ES6 import in the same file (at least not easily), so if you're using ES6 import and wish to read a file, do so with fs.readFileSync or a similar method. If the file is a json string, you'll need to parse it with JSON.parse().
If you want to use ES6 (NOT CommonJS) module system but want to use the Node.js version which is less than V18 (supports direct json import) then use the below approach.
import { createRequire } from "module";
const require = createRequire(import.meta.url); // construct the require method
const data = require("users.json"); // Now you can use require method in ES6
console.log(data)
Newbie Node question here.
I'm trying to use the Google Cloud Node client with an existing application (not written by me) that bundles its code with rollup.
I've tried importing the library with require, as per its documentation, as follows:
import REGL from "regl/dist/regl";
import Camera from "./lib/camera";
...
var gcloud = require('google-cloud');
But my application complains (CLARIFICATION: it only starts producing this error when I add the require statement, otherwise the imports work fine):
'import' and 'export' may only appear at the top level
So maybe I need to use import gcloud instead of require, but how? I tried looking at the code in node_modules and doing this instead:
import gcloud from "google-cloud/src/index";
But now I get a bunch of other errors
🚨 Unexpected token
node_modules/google-cloud/node_modules/ent/reversed.json (2:7)
1: {
2: "9": "Tab;",
^
How can I use import instead of require, or alternatively, how can I make require play nicely with import?
import is ES6 syntax. You either must use an experimental flag with nodejs or use babel to compile your js to be ES6 compatible.
EDIT:
Since the problem is with require and not import, i'm updating my answer.
I'm not sure what you're setup is but it's because, i'm guessing, google-cloud isn't written in es6. So you'll have to see if there's an es6 version in the src. If there is you could try (I doubt this will work)
Try:
import * as gcloud from 'google-cloud'
if that doesn't work - try a shimming module like riveted. You'll need webpack to compile this. Since you're using rollup.js, which i'm unfamiliar with you'll need a es5 to es6 compiler for this.
I want to use es6's import, require and export in my web app using codeigniter.
i found babel-standalone but it's not working.screenshot of embed js files
With the added detail that
import, require and export is undefined
Here's the problem: that's not what Babel does. Babel transpiles code: it turns one file of ES6 code into a file that contains ES5 code that does the same thing. It does not combine source code files that use require or import into bundles.
You're looking for browserify or Webpack to do that - they are bundlers, tools that let you use require, import, and export to organize code. You'll need to use one of them to accomplish your goal - Babel alone will not do what you're trying to do.