Guidelines on incorporating HTML files as templates into Rollup and compiling them into concatenated strings

I am currently working on setting up a build process for Optimizely experiments using Rollup instead of Webpack. The reason for this change is that the code exported by Webpack is too bloated for our specific use case. My goal is to import .html files as templates and then compile them into concatenated strings that are compatible with ES5 in my Rollup/Babel build.

Although I have experimented with some template plugins listed on https://github.com/rollup/awesome#templating, I am hesitant to add another module library as a dependency for each experiment. While I have managed to import HTML files as template literals using a couple of plugins, they do not get compiled into ES5 compatible strings by Babel. It seems that Babel only compiles inline template literals to concatenated strings, and external HTML strings are left out. I suspect this might be a configuration issue with Babel.

In our current Webpack build process, we utilize the html-es6-template-loader which has built-in compilation capabilities to generate ES5 compatible string concatenation effortlessly. It would be great to find something similar for Rollup.

Here is my current configuration, using posthtml, although I have tried other plugins with the same outcome:

import babel from 'rollup-plugin-babel';
import posthtml from 'rollup-plugin-posthtml-template';

export default {
    input: './src/index',
    output: {
        file: './dist/index.js',
        format: 'cjs'
    },
    plugins: [
        posthtml({
            template: true
        }),
        babel({
            exclude: 'node_modules/**',
            presets: ['@babel/preset-env']
        })
    ]
}

The ideal scenario would involve starting with an HTML file as a template with ES6 ${} syntax, importing it into a JS file, and then compiling it into a JS file with inline concatenated strings.

template.html:

<div class="some-div">hello ${data.entity}</div>

index.js in modern ES version:

import template from './template.html';
console.log(template({entity="world"})); // logs: <div class="some-div">hello world</div>

The desired outcome is to have the compiled script be compatible with ES5 without requiring additional templating code. The result should resemble something like the code below:

var template = function(data){
  return '<div class="some-div">hello ' + data.entity + '</div>';
}
console.log(template({entity="world"})); // logs: <div class="some-div">hello world</div>

Answer №1

If you're looking to bring in .html files as strings, another option to consider is the rollup-plugin-html:

// rollup.config.js
import html from "rollup-plugin-html";

export default {
  input: "./index.js",
  plugins: [
    html({
      include: "**/*.html",
    }),
  ],
  output: {
    file: "my-module.js",
    name: "MyModule",
    format: "umd",
  },
};

Answer №2

After some troubleshooting, I managed to find the solution. Interestingly, it required me to incorporate HTML into the babel configuration. Initially, I hadn't considered this step necessary, assuming that babel only processed the JS file post-import and conversion to a template literal. However, it appears that this addition is crucial.

This realization came to me as I was browsing through the documentation on external dependencies for rollup-plugin-babel

babel({
    exclude: 'node_modules/**',
    presets: ['@babel/preset-env'],
    extensions: ['.js', '.html']
})

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

Newbie struggling with executing JavaScript in Visual Studio Code

Hey there! I'm new to coding and have been struggling for the past couple of hours trying to get a simple JavaScript code to run on VSC. Can anyone lend a hand in helping me set up my sandbox correctly? Here's a snapshot for reference: https://i ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

When utilizing div.load, jQuery and other JavaScript sources may not be defined

When you load a page using jQuery load: $("#myDiv").load("page.php",{foo: bar}); The head section is included in the index: <head> <script src="/assets/plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="/assets/plugi ...

I need to press the button two times to successfully submit

I am experiencing a remote validation issue. When I click on the submit button without focusing on the text box, it triggers a remote ajax call for validation. However, when I press the submit button a second time, the form gets submitted. On the same cl ...

Create a specific website link for searching on YouTube

Is there a way to generate a YouTube URL using JavaScript or PHP that searches for videos on a specific user account and displays the best title match at the top of the search results? This is the code I am currently using: <!DOCTYPE html> <head ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

Exploring the capabilities of AngularJS directives through ng-html2js testing

Many questions have been raised about the ng-html2js plugin, but unfortunately, none of the answers provided were able to solve my specific issue. I meticulously followed the official installation guide and also referenced the example available at https:/ ...

Issue with Rails manifest assets being undefined or not recognized as an object when making an AJAX request in Internet Explorer 8

I am attempting to retrieve the file names of certain files using ajax from the Manifest.json file. Our file names are digested, which is why I need to access them this way in order to use ajax later on. Here is the code snippet I am currently using: $.aj ...

Guide to verifying the presence of cookies by name in the browser and granting access to the specific page accordingly

In the process of developing an authorization system with Express, Node, and MySQL, I decided to utilize JWT tokens for user authorization. After successfully storing the JWT token in cookies, my next step is to verify if the token exists in the cookie b ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

Showing a gallery of images in React

I have a unique situation where I am working on setting a variable to match the import statement that calls for images. Once I have this variable assigned, I want to use it to display the corresponding image. For instance, if my code generates the name &ap ...

Refresh the content with an embedded iframe

I am attempting to update the body content by removing all existing content and inserting an iframe: function create_custom_iframe(target){ var iframe = document.createElement('iframe'); iframe.setAttribute('id', 'target_u ...

How to ensure that the iframe is completely loaded before proceeding with Selenium JavaScript

I have a webpage that displays an iframe, within the iframe there is a spinning spinner (overlying the fields). My approach involves using selenium to navigate to the iframe, return this.driver.wait(function() { return self.webdriver.until.ableToSw ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

Determine the number of Fridays that fall between two dates using JavaScript or jQuery

Can you help me calculate the total number of a specific day between two given dates? For instance, if I have a start date and end date stored in a variable, I would like to know how many Fridays fall within that timeframe. ...

What is the best way to retrieve certain fields from a Firestore database using Next.js?

Is there a way to access a specific field in a document using the user's uid as its name? I am utilizing useAuthState from react-firebase-hooks to retrieve the user's credentials (uid). https://i.sstatic.net/t1xGL.png This code snippet allows me ...