使用JavaScript导入节点模块 [英] Importing Node Modules With JavaScript

查看:48
本文介绍了使用JavaScript导入节点模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个简单的问题,我深表歉意,但是我对Web开发和JavaScript还是陌生的.

I apologize for the simple question, but I'm pretty new to web development and JavaScript.

我要导入使用npm安装的软件包,具体请按照此处的指南进行shopify-buy的购买:

I want to import a package I've installed using npm, specifically shopify-buy following the guide here: https://shopify.github.io/js-buy-sdk/

该软件包位于我的node_modules文件夹中,我正在尝试使用 import Client from'shopify-buy';

The package is in my node_modules folder and I'm trying to import it into a JavaScript document using import Client from 'shopify-buy';

当我尝试在Chrome中加载所有内容时,我在导入行上收到错误消息

When I try to load everything up in Chrome, I get an error on the import line

Uncaught SyntaxError: Unexpected identifier

Firefox错误有点不同: import声明只能出现在顶层

The Firefox error is a bit different: import declarations may only appear at top level

我在做什么错了?

导入行是我的JavaScript文件中的第一行.而且我的HTML文件已正确链接到JS文件(我认为).

The import line is the first line in my JavaScript file. And my HTML file is properly linked to the JS file (I think).

shopify.js

// Functions for SHOPIFY
import Client from 'shopify-buy';

const client = Client.buildClient({
    domain: 'xxxxx.myshopify.com',
    storefrontAccessToken: 'xxxxx'
});

index.html

<script src="javascript/shopify.js"></script>

推荐答案

如果您想通过语法使用npm模块,例如从某物"中导入sth 用于浏览器,则需要设置模块捆绑器和ES6编译器,例如Webpack和Babel.您需要搜索它们,并找到相应的教程来设置它们.

If you want to use npm modules via the syntax, like import sth from "something" for browsers, you'd need to set up a module bundler and ES6 compiler, such as Webpack and Babel. You'd need to google them and find tutorials for setting up them accordingly.

使用SDK的一种简单方法似乎是使用CDN,因为它已经为浏览器所理解.像这样:

An easy way to use the SDK seems to be using the CDN, since it's already been built for browsers to understand. Something like:

index.html

<script src="http://sdks.shopifycdn.com/js-buy-sdk/v1/latest/index.umd.min.js"></script>
<script src="javascript/shopify.js"></script>

shopify.js

const client = ShopifyBuy.buildClient({
    domain: 'your-shop-name.myshopify.com',
    storefrontAccessToken: 'your-storefront-access-token'
});

console.log(client); 

这篇关于使用JavaScript导入节点模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆