1
votes

I have a payments directory with two files: constants.js and controller.js

constants.js:

export const STRIPE_CONSTANTS = {
  USD: 'usd',
  SKU: 'sku',
};

export const SKU_CONSTANTS = {
  first_sku: 'sku_abc123',
};

and in my controller.js, I import, but get an error:

import { STRIPE_CONSTANTS, SKU_CONSTANTS } from './constants';

(function (exports, require, module, __filename, __dirname) { import { STRIPE_CONSTANTS, SKU_CONSTANTS } from './constants'; ^

SyntaxError: Unexpected token {

What am I doing wrong here? Thanks.

1

1 Answers

4
votes

Looks like you are executing the code using node runtime which has not implemented the ES modules yet. ( This would run on browsers though if you are using a transpiler first to convert from ES6 to ES5)

You need to use require to import the module and exports to export them.

ES modules been implemented in node 8.5.0 and later but the caveat is that the file name should end with .mjs instead so that they don't break existing code.

constants.js

const STRIPE_CONSTANTS = {
  USD: 'usd',
  SKU: 'sku',
};

const SKU_CONSTANTS = {
  first_sku: 'sku_abc123',
};

exports.STRIPE_CONSTANTS = STRIPE_CONSTANTS;
exports.SKU_CONSTANTS = SKU_CONSTANTS;

// If you want to export it as an object instead of that you 
// can use destructing when importing them you can use `module.exports`
// instead

module.exports = {
   STRIPE_CONSTANTS,
   SKU_CONSTANTS
}

controller.js

const constants = require('./constants');

const STRIPE_CONSTANTS = constants.STRIPE_CONSTANTS;
const SKU_CONSTANTS = constants.SKU_CONSTANTS;

// If constants was exported as an object using `module.exports`
// you can use destructing instead

const { STRIPE_CONSTANTS, SKU_CONSTANTS } = require('./constants');