Skip to content

Instantly share code, notes, and snippets.

@Stayl045
Forked from ashx3s/README.md
Created March 17, 2022 14:45
Show Gist options
  • Save Stayl045/b9efe239d57a593f73a33cced8ab88e2 to your computer and use it in GitHub Desktop.
Save Stayl045/b9efe239d57a593f73a33cced8ab88e2 to your computer and use it in GitHub Desktop.
Javascript Imports and Exports

How to import javascript files into one another

Common JS Module System

module.exports/require

  • This is the older way that node would import files into one another.
  • Use it with normal javascript files. This works whether you have a package.json or not
  • Some node packages may not be compatible with this syntax. But it is still in use

Example:

  • In your import file (script.js)
const tasks = require('./taskList.js)
  • Your export file would look something like this
module.exports = {
  tasks: [
    // output content here
  ]
}

ES6 Syntax

import/export

  • This is the newer syntax and is focused on modules
  • If you are in a node project, "type: "module" should be in your package.json
  • Otherwise you can use this syntax by giving files the .mjs file extension
  • Vue and Nuxt use this style of imports

Example (Using .mjs files)

  • import file (script.mjs)
import { tasks } from './taskList.mjs'
  • export file (tasList.mjs)
export const tasks = [
  // array here
]
  • note that an array is not necessary, it is just the content type used in these examples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment