nodejs Import require conversion

可紊 提交于 2019-12-23 20:52:30

问题


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...


回答1:


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.




回答2:


It's interesting that the original syntax

var stuff = require('some_module')

is not working for you. If your app was scaffolded from Angular CLI then it should support both imports and require statements out of the box.

for example, I'm using MSR in an Angular 2 component like this:

var MediaStreamRecorder = require('msr');


来源:https://stackoverflow.com/questions/42406913/nodejs-import-require-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!