Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs Import require conversion

Learning NodeJs here. Problem is when I tried to search for answers, I am not finding what I am looking for. Probably because this is too basic or non-issue.

I am working on nodejs with angular2. So naturally, I have things like:

import { stuff } from 'some_module'

But I am trying to work with a package that has usage example of:

var stuff = require('some_module')

Obviously, my code didn't work when I use import etc. else I wouldn't be posting here. Is it because I am doing something wrong? Or am I out of luck such that this particular module doesn't work with import? Can someone shed some light on how to write proper import statements when I see usage sample of require('some_stuff'), so I can use other modules I download from npm?

thanks in advance.

EDIT: So I tried npm install requirejs --save. Then I wrote the require statement above. But I am getting a 404 on the package...

like image 584
user691856 Avatar asked Feb 23 '17 04:02

user691856


Video Answer


1 Answers

You can use import but you have to run your app with babel.

you have to add this line to your package.json file

"scripts": {
    "start": "NODE_ENV=production node_modules/.bin/babel-node --presets 'es2015' src/server.js",  
    "build": "NODE_ENV=production node_modules/.bin/webpack -p"
  },
  "dependencies": {
    "babel-cli": "^6.11.4",
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.13.2"
  },
  "devDependencies": {
    "http-server": "^0.9.0",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.14.1"
  }

src/server.js file is your main file location

and then run file with following command

npm run start

when you use import { stuff } from 'module'; then you can directly use stuff() in your program.

but when you use var stuff = require('module'); then you need to do stuff.stuff() in your program.

like image 141
Shubham Batra Avatar answered Sep 22 '22 00:09

Shubham Batra