[英]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. 我正在尝试将Google Cloud Node客户端与将其代码与汇总捆绑在一起的现有应用程序(不是我编写的)一起使用。
I've tried importing the library with require, as per its documentation, as follows: 我已经尝试按照其文档使用require导入库,如下所示:
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): 但是我的应用程序抱怨(澄清:仅当我添加require
语句时,它才开始产生此错误,否则导入工作正常):
'import' and 'export' may only appear at the top level
So maybe I need to use import gcloud
instead of require
, but how? 因此,也许我需要使用import gcloud
而不是require
,但是如何? I tried looking at the code in node_modules
and doing this instead: 我尝试查看node_modules
中的代码并node_modules
执行此操作:
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
代替require
,或者如何使require
与import
完美配合?
import is ES6 syntax. import是ES6语法。 You either must use an experimental flag with nodejs or use babel to compile your js to be ES6 compatible. 您必须在nodejs中使用实验性标志,或者使用babel来编译js以使其与ES6兼容。
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. 我不确定您要设置的是什么,但这是因为我猜测google-cloud不是用es6编写的。 So you'll have to see if there's an es6 version in the src. 因此,您必须查看src中是否有es6版本。 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. 您将需要webpack进行编译。 Since you're using rollup.js, which i'm unfamiliar with you'll need a es5 to es6 compiler for this. 由于您使用的是rollup.js,我对此并不熟悉,因此需要使用es5到es6编译器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.