vcapra1
vcapra1

Reputation: 2025

How to create basic Node.js project with materialwebcomponents?

I am relatively new to Node.js. This is a very simple program so far, meant to just test the incorporation of material-components-web. I followed the instructions step-by-step in the readme, and this is what I have so far:

package.json

{
  "name": "hello-polymer", "version": "0.1.0",
  "description": "Intro to Polymer", "main": "index.js",
  "scripts": { "start": "node index.js" },
  "author": "vcapra1", "license": "ISC",
  "dependencies": { "@webcomponents/webcomponentsjs": "^2.0.2" }
}

index.js

http = require('http')
fs = require('fs')

http.createServer((request, response) => {
  response.statusCode = 200
  response.setHeader('Content-Type', 'text/html')
  let filename = "./" + request.url
  if (request.url.startsWith("/@")) {
    filename = "./node_modules/" + request.url
  } else if (request.url == "/") {
    filename = "./index.html"
  } else {
    response.statusCode = 404;
    response.end("404 Not Found");
  }
  fs.readFile(filename, (err, data) => {
    console.log("Request: ", request.url);
    response.end(data)
  })
}).listen(3000)

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>MWC Test</title>
    <script src="@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
    <script type="module" src="@material/mwc-icon/mwc-icon.js"></script>
  </head>
  <body>
    Hello, World
    <mwc-icon>sentiment_very_satisfied</mwc-icon>
  </body>
</html>

Then I run the following command in the project folder:

polymer serve

I've also tried starting it with npm using:

npm start

Both commands allow me to go to the webpage at http://localhost:XXXX, but each time all I get is the text "Hello, World sentiment_very_satisfied", and the plain text stays there with no icon.

I'm not really sure what I'm missing. I find it strange that the script src attributes reference @webcomponents as a sibling folder while said folder is actually in the node_modules directory, so I tried changing that, but still no luck.

Upvotes: 3

Views: 510

Answers (1)

Kable
Kable

Reputation: 1035

I got it working by running with

polymer serve --module-resolution=node --npm.

This tells polymer-cli to transform npm style references to relative references when serving files. Although it doesn't work for index.html for some reason, so relative paths are required there:

<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module" src="node_modules/@material/mwc-icon/mwc-icon.js"></script>

You can read more here https://www.polymer-project.org/blog/2018-03-23-polymer-3-latest-preview#packagenames

Upvotes: 1

Related Questions