Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Node Modules With JavaScript

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

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/

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';

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

Uncaught SyntaxError: Unexpected identifier

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

What am I doing wrong?

Edit:

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>
like image 409
Kyle2595 Avatar asked Feb 28 '18 03:02

Kyle2595


People also ask

Can you use node modules in JavaScript?

Being able to run a node module on the browser is extremely beneficial. Users can use already existing modules on the client side JavaScript application without having to use a server.

Can you use import in node JS?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

Can I use import in JavaScript?

Introduction to the JavaScript import()The import() allows you to dynamically import a module when needed. Here is how the import() works: The import() accepts a module specifier ( moduleSpecifier ) that has the same format as the module specifier used for the import statement.


1 Answers

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.

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); 
like image 188
Ippei Tanaka Avatar answered Sep 30 '22 17:09

Ippei Tanaka