What is the Node.js 'require' equivalent to the following ES6 import?
import RNFetchBlob from 'react-native-fetch-blob'
Thank you
There's no default export in require so you don't have an exact equivalent.
The practice with node modules when you have only one value to export is to make it the module exports:
module.exports = ...
In such a case, you'll be able to import using
var RNFetchBlob = require('react-native-fetch-blob');
Solution
I got it working with:
var RNFetchBlob = require('react-native-fetch-blob').default;
For more details, check out this.
Related
In my node.js (express.js) project, I try to wrap axios to create a HttpClient like this:
import axios from 'axios';
const httpClient = axios.create({ baseURL: 'http://locahost:3003' });
...
export const httpClient = {
...
};
When I run it, I get error SyntaxError: Cannot use import statement outside a module which complains the line import axios from 'axios'. How can I get rid of this error? (I come from React-native world, I used the same thing in React-Native, it is fine)
The issue is by default express uses CJS format of importing as you might have seen const axios = require("axios").
What you are trying to do is an ESM format of import which is not understood by the JS as natively. To work import statements you can either add the following property to your package.json file - "type": "module" or you can use ".mjs" extension instead of default ".js" extension.
Hope this link helps further.
On Node 13.8 I'm trying to use import / export.
EG:
import {ChatClient, Message, MessageParser} from './chat-client/module.js';
But when i do this, I get
SyntaxError: Cannot use import statement outside a module
So in my package.json I set "type" : "module" but now when I try to use const io = require('socket.io-client');
I get ReferenceError: require is not defined
Is there a way to use import / export AND require?
The original error, does that just mean I have to wrap my library in a NPM library? It's a Library that's used both front end and backend so using import / export is important.
Thanks
As the documentation says:
No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.
https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname
You can't use both natively. If you want to do that use Babel to transpile your code.
ES Modules in Node >= 14 do not support require.
However if you want to add it, u have to add this at the top of your file:
Everything should work fine.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Several points:
Use .mjs instead of .js.
Never use require.
It is optional to use "type": "module".
If you use {"type":"module"} you won't be able to use require function in your project. So if you want to use require as well import you need to add the following properties in package.json.
"babel": {
"presets": [
"stage-3",
"latest"
]
}
"babel-preset-latest": "^6.16.0"
"babel-preset-stage-3": "^6.5.0"
I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5
I'm using Intellij Idea to create a NodeJs application in ES6.
My node.exe version is version 6.4.0
I created a simple class :
//wNodeClasses.js
'use strict';
export class wsUrl
{
constructor()
{}
}
I import the module in another file :
require('../../../Root/Libs/Waldata/wsNodeClasses');
When I start the application I always get the error :
d:\Dev\webDev\Root\Libs\Waldata\wsNodeClasses.js:11
export class wsUrl
^^^^^^
SyntaxError: Unexpected token export
at Object.exports.runInThisContext (vm.js:76:16)
I don't use any transpiler , I want to write "pure ES6 code" (I don't want to use Babel or any equivalent)
I understand that NodeJs 6.4.0 can interpret directly ES6 code
Here is my Node.Exe command line :
-max-old-space-size=8192 --expose_debug_as=v8debug
I am a newbie, I suppose I'm missing something obvious, I googled around and I didn't found an answer
I finally found the issue.
NodeJs 6.4.0 with chrome V8 doesn't support Es6 "export" keyword or syntax.
I found a work around using
//Module file
module.exports=
class wsUrl
{
}
and in the consumer :
var wsUrl = require('../../../Root/Libs/Waldata/wsNodeClasses');
...
var MyVar = wsUrl new("test");
I'm still searching to have multiple classes in a same Js file (module) and export them
Thanks for your answer.
I used a different technic (I assume it's just a matter of personal preference) :
//In the module module.exports.myClass1=class myClass1{}
module.exports.myClass2=class myClass2{}
//In the main file (consumer)
var myModule = require('../../../Root/Libs/Waldata/wsNodeClasses');
...
var test=new myModule .wsUrl("param");
This works for me with NodeJs 6.4.0 and intellij (or webstorm)
PS :I'm adding an answer, because I had problems formatting my comment (could not make a "line break"
I'm trying to use Markdown-it in Ember Helper. First I installed it with Bower and tried to import it.
app.import('bower_components/markdown-it/dist/markdown-it.js');
In helper:
import MarkdownIt from "markdown-it";
This is showing error Could not find module: markdown-it. Then I tried to use Ember-browserify and install Markdown-it via npm. I tried to import it in helper
import MarkdownIt from "npm:markdown-it";
export default Ember.Handlebars.makeBoundHelper(function(input){
var result = MarkdownIt.render(input);
return new Ember.Handlebars.SafeString(result);
});
This is showing error TypeError: a.default.render is not a function.
I also tried
import MarkdownIt from "npm:markdown-it";
export default Ember.Handlebars.makeBoundHelper(function(input){
var md = new MarkdownIt();
var result = md.render(input);
return new Ember.Handlebars.SafeString(result);
});
This is showing Error: Could not find module npm:markdown-it imported from my-new-app/helpers/format-markdown
The library you're trying to use doesn't provide a name for itself when using AMD, so there's no way to import it via a name. See https://github.com/ember-cli/ember-cli/issues/770 for more information about this.
It does look like "markdown-it" also exposes itself as a global, so you can always access it that way: