nodejs Import require conversion

2019-07-13 00:14发布

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

2条回答
孤傲高冷的网名
2楼-- · 2019-07-13 00:42

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.

查看更多
爷的心禁止访问
3楼-- · 2019-07-13 00:49

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');
查看更多
登录 后发表回答