Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment.
My main goal is to execute everything from IIS Express.

However, I'm encountering the following problem:

Uncaught TypeError: Failed to resolve module specifier "@polymer/polymer/polymer-element.js".
Relative references must start with "/", "./", or "../".


Let me share my code: Index.cshtml:

    <head>
    <script src="~/Scripts/PolymerApp/node_modules/@("@webcomponents")/webcomponentsjs/webco
       mponents-loader.js"></script>
       <script type="module" src="~/Scripts/PolymerApp/first-element.js">
       </script>
    </head>

    <h2>Index</h2>
    <div>
        <first-element></first-element>
    </div>


This is my first-element.js:

 import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';

class FirstElement extends PolymerElement {
  static get template() {
    return html`
      <style>
        :host {
          display: block;
        }
      </style>
      <h2>Hello [[prop1]]!</h2>
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'first-element',
      },
    };
  }
}

window.customElements.define('first-element', FirstElement);


I used the command prompt to create this with: polymer init and then selected the element template. When I run it through polymer serve on localhost, it works perfectly fine which leads me to believe there might be some build process involved.
Thank you for your help in advance. I hope I have provided all the necessary information.

Answer №1

After multiple attempts to replace a string in the html file generated by Polymer using webpack and a plugin, it appears that the file cannot be located. Perhaps someone with more expertise in Webpack can help resolve this issue.

// Updated webpack.config.js
var webpack = require('webpack');
const ReplaceInFileWebpackPlugin = require('replace-in-file-webpack-plugin');

"use strict";

module.exports = {
    entry: {
        main: '/'
    },
    output: {
        filename: "./wwwroot/dist/[name].bundle.js",
        publicPath: "/temp/"
    },
    devServer: {
        contentBase: ".",
        host: "localhost",
        port: 9000
    }, mode: "development",
    plugins: [
        new ReplaceInFileWebpackPlugin([{
            dir: './path/to/polymer-built-app/build/default/',
            test: /\.html$/,
            rules: [{
                search: '/@webcomponents/',
                replace: '/@{\'@webcomponents\'}/'
            }]
        }])
    ]
};

**UPDATE: August 4th, 2018 **

I've made some progress:

/// <binding BeforeBuild='Run - Development' />
// Updated webpack.config.js
var webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackStringReplacePlugin = require('html-webpack-string-replace-plugin');

"use strict";

module.exports = {
    entry: {
        main: './'
    },
    output: {
        publicPath: '/',
        path: path.resolve(__dirname, 'wwwroot'),
        filename: "./dist/[name].bundle.js"
    },
    devServer: {
        contentBase: ".",
        host: "localhost",
        port: 9000
    },
    mode: "development",
    plugins: [
        new HtmlWebpackPlugin({
            "template": "./path/to/index.html",
            "filename": "../path/to/Views/Shared/_PolymerLayout.cshtml"
        }),
        new HtmlWebpackStringReplacePlugin({
            '@webcomponents':
                '@Html.Raw("@webcomponents")',
            '%40webcomponents':
                '@Html.Raw("@webcomponents")',
            '%40polymer':
                '@Html.Raw("@polymer")',
            '/node_modules/':
                '/path/to/node_modules/',
            './src/path/to/polymer-app',
            '<!-- See google short url -->':
                '<!-- See google short url -->\r\n<base href="/custom/base/ref">'
        })
    ]
};

Answer №2

When you start the .js import path like this:

from '@polymer/...'

Polymer 3 provides a convenient command called "polymer build" that automatically converts the path to the correct location: Before:

from '@polymer/polymer/polymer-element.js';

After:

from "./node_modules/@polymer/polymer/polymer-element.js";

To avoid using the polymer build command line tool, you can simply add ./node_modules/ at the beginning of your path.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...

NodeJs: Transforming strings into UUID v4 efficiently

Suppose I have the following string: const input = '83e54feeeb444c7484b3c7a81b5ba2fd'; I want to transform it into a UUID v4 format as shown below: 83e54fee-eb44-4c74-84b3-c7a81b5ba2fd My current approach involves using a custom function: funct ...

Leverage Express JS to prevent unauthorized requests from the Client Side

Exploring the functionalities of the Express router: const express = require("express"); const router = express.Router(); const DUMMY_PLACES = [ { id: "p1", title: "Empire State Building", description: "One of the most famous sky scrapers i ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...

Retrieve the link of a nearby element

My goal is to create a userscript that has the following functionalities: Add a checkbox next to each hyperlink When the checkbox is clicked, change the state of the corresponding hyperlink to "visited" by changing its color from blue to violet. However ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Refresh the page when the parameter in the URL changes

I'm encountering a small issue that I can't seem to resolve. Currently, I am on the following page: http://example.com:8080/#/user/5ad142e8063ebb0537c5343e There is a link on this page that points to the URL below: http://example.com:8080/#/u ...

Is there a way to locate and delete an image element with a broken hyperlink?

My website is currently hosted on Wordpress, and I've noticed that there is an issue with a broken image link on my site. I'm not sure when this occurred, but it seems to only be affecting the post section of my site. https://i.sstatic.net/iarDU ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

I keep encountering the issue where nothing seems to be accessible

I encountered an error while working on a project using React and Typescript. The error message reads: "export 'useTableProps' (reexported as 'useTableProps') was not found in './useTable' (possible exports: useTable)". It ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Guide to loading an image and incorporating it into a canvas using Gatsby's server-side rendering

I encountered an issue where I was unable to create an image using any of the supported types like CSSImageValue, HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, or OffscreenCanvas in my SSR application with Gatsby. De ...

What are the steps for defining a package once and utilizing it across multiple pages?

Hello, I'm new to Next.js and I have a question regarding the code organization. In my project, I have two pages: PostList (index.js) and PostSingle ([postId].js). I want to implement a feature that allows users to switch between dark and light theme ...

Managing User Feedback with Ajax, JQuery, and PHP

Imagine you're using ajax to send data. The server processes it (in PHP) and sends back a response that can be captured with complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) } The big question is: how can you modify ...