Inserting variables into HTML and JavaScript with Webpack

Ksenia Coulter
DailyJS
Published in
5 min readOct 17, 2017

This is a walkthrough on how to use webpack to insert variables from a file into HTML or JavaScript. No prior knowledge of webpack, node, or git is required to follow along. My goal is to be as granular as possible, so please let me know if I skipped over a part.

Webpack has been growing in popularity as a way for developers to manage their build process. Webpack is a module bundler that allows your code to be split into smaller chunks — modules, leading to more maintainable code and slicker performance. In this article I’ll walk you through installing and setting up webpack in a project, downloading and configuring webpack plugins, and using a separate variable file in both HTML and CSS.

Problem: I’m working on an application that will be used by multiple clients. As little as possible needs to be hard coded and variables that differ between clients need to be in one place for an easy swap. (Think facebook app ID, various analytics platform ID’s, primary language of the website, etc.)

Step 1: starting from scratch

If you don’t have node/npm installed and you have a mac read this, if you have windows read this.

Create a project. Either create a new repository if you’re familiar with git/github, or just make a new folder. Open your terminal and navigate to that project folder. Then run:

npm init -y

Running npm init initiates Node Package Manager (NPM) and generates a package.json file in this directory, -y is just a flag that skips setup questions and initiates npm with default presets. You should see something like this:

Now that npm has been initiated, you can use it to install webpack.

npm install --save webpack

Now when you look in the project directory, you can see a new folder called node_modules. When I first opened it I was surprised to see so many files. I expected the file structure to be node_modules/webpack/... with all the dependencies needed by webpack inside the webpack directory. Turns out npm aims to install dependencies maximally flat, if you’re curious as to why, you can read more about it here. (If you’re using git/github now is a good time to add the node modules to your .gitignore file so you don’t commit them by accident).

In addition to node modules, you’ll notice a new line in your package.json file.

"dependencies": {
"webpack": "^3.6.0"
}

Ok, now let’s actually create files we’ll be working on. You can either use your text editor or the terminal to create index.html, src/index.js, and webpack.config.js

mkdir src
touch src/index.js
touch index.html
touch webpack.config.js

From the webpack docs, here’s the initial setup of webpack config:

The entry point tells webpack where to start and follows the graph of dependencies to know what to bundle. You can think of your application’s entry point as the contextual root or the first file to kick off your app.

In the example above, we use the output.filename and the output.path properties to tell webpack the name of our bundle and where we want it to be emitted to.

https://webpack.js.org/concepts/#entry

Basically, when you run webpack, it will bundle your various js files and create a file called bundle.js

Let’s go ahead and do that. The webpack documentation says to run the commandwebpack in your terminal. However, this did not work for me. I got command not found: webpack. After some Googling I found something this StackOverflow answer that helped me (usually the issue is not installing modules globally, but in my case my paths were wrong and I had to add the correct path to my bash_profile). In your package.json file add this line:

"scripts": {
"start": "webpack"
}

Now you can run npm start to trigger the webpack command. Once your run this, you should see a new folder dist with bundle.js inside. Take a look in it, there’s some boilerplate webpack code.

Now is the time to use our first webpack plugin.

npm install html-webpack-plugin --save

Now package.json should have two dependencies, like this:

"dependencies": {
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.6.0"
}

Now we have to get that plugin into our webpack config. First we’re going to require it and save it as a constant. Then we’re going to add it to an array of plug ins. At the end your webpack.config.js should look like this:

The template points this plugin to the right HTML file, if you want it to create a new file from a template you need to also specify a filename. Read about more options in the docs.

So now we’re finally ready make our HTML more generic and use variables instead of hard coding values. Let’s create a variables.js file in the root directory of the project. Now let’s set some variables.

//This is the entire contents of variables.jsmodule.exports = {
language: 'en',
word: "defenestration",
pattern: /([A-Z])\w+/
}

Since this is javascript, we can store anything as a variable — strings, numbers, functions, regular expressions, objects, etc.

In your webpack.config.js file add this line after HtmlWebpackPlugin require statement.

const variables = require('./variables.js');

This imports your variables and saves them into a constant variables. You can now use HtmlWebpackPlugin to display your favorite word in HTML like so:

If you’ve used Ruby you’ll recognize <%= %> syntax. These funky brackets just tells the compiler that the text inside is not HTML. You may also be familiar with the JavaScript function JSON.stringify(). The function converts a JavaScript value to a JSON string — this is just quirk of the plugin, your word will not display in your HTML otherwise.

If you run npm start now, you’ll see a new HTML file appear in dist directory. Look to make sure that file has your favWord.

Great, we’ve been able to use a variable to render HTML dynamically. Now let’s see how we can use those same variables in the JavaScript files. This part is very straight forward. All you have to do is require the variable file inside your JavaScript file just like we did in the webpack config file.

const variables = require('../variables.js');console.log(variables.word);

Once again, run npm start so that webpack can get your changes into the bundle.js

Now when you open your index.html in a browser you should see something like this:

You can find the finished product here:
https://github.com/kscoulter/webpack-html

Nowhere but up from here :)

Please let me know if this was a helpful walkthrough and if there are still points of confusion you’d like to have clarified.

--

--

Ksenia Coulter
DailyJS

Web developer @washingtonpost. Dancer. Adventurer. Striving to amplify minority voices in tech. #dctech #womenintech #webdev