简体   繁体   中英

Use “import” with Node library, rather than “require”?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM