Skip to content Skip to sidebar Skip to footer

How To Use Static Imports In Glitch?

For the life of me, I can't understand how to use ES6 static imports in a simple Glitch.com project. I found this project where someone uses a static import with no extra node modu

Solution 1:

The Glitch project you linked from Flavio is a static site with no backend, package.json or server. It's a great example of ES6 modules but if you're working with Express (I assume so based on its presence in your package.json), converting the example may be non-obvious.

I notice you also have TS in your package.json, but I don't want to be too presumptuous so I'll stick to vanilla in the interests of communicating the simplest possible setup. Try it on Glitch.

Directory structure:

public
  math
    add.js
  index.js
  style.css
views
  index.html
server.js
package.json

public/math/add.js:

export default (a, b) => a + b;

public/index.js:

import add from "./math/add.js";

document.body.textContent = `1 + 2 = ${add(1, 2)}`;

views/index.html, main modification is adding type="module" to the <script> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="A cool thing made with Glitch">
    <title>Welcome to Glitch!</title>
    <link id="fav"  href="https://glitch.com/edit/fav-app.ico" type="image/x-">
    <link  href="/style.css">
    <script type="module" src="/index.js"></script>
  </head>
  <body>
  </body>
</html>

server.js, basically unmodified from the default:

const express = require("express");
const app = express();

app.use(express.static("public"));

app.get("/", (request, response) => {
  response.sendFile(__dirname + "/views/index.html");
});

const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

package.json, also unmodified from the default:

{
  "//1": "describes your app and its dependencies",
  "//2": "https://docs.npmjs.com/files/package.json",
  "//3": "updating this file will download and update your packages",
  "name": "hello-express",
  "version": "0.0.1",
  "description": "A simple Node app built on Express, instantly up and running.",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "engines": {
    "node": "12.x"
  },
  "repository": {
    "url": "https://glitch.com/edit/#!/hello-express"
  },
  "license": "MIT",
  "keywords": [
    "node",
    "glitch",
    "express"
  ]
}

Post a Comment for "How To Use Static Imports In Glitch?"