webpack


Use HTMLWebpackPlugin with an EJS file


I want to use the HTMLWebpackPlugin to take my index.ejs template file, insert my bundled assets, and output a final index.ejs file.
This example has a EJS variable <%= API_URL %>, but webpack is interpreting it.
How can I stop webpack from substituting the variable?
Starting "template":
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Monitor</title>
<script>
window.config = {
API_URL: "<%= API_URL %>"
}
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>
When you try to run webpack:
ERROR in Template execution failed: ReferenceError: API_URL is not defined
Desired result index.ejs: (has bundled assets and EJS var)
Monitor
window.config = {
API_URL: "<%= API_URL %>"
}
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
bundle: './src/index.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
// CSS is imported in app.js.
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: ["css-loader", "sass-loader"]
})
}]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'API_URL': JSON.stringify(process.env.API_URL)
}
}),
new HtmlWebpackPlugin({
template: 'src/index.ejs',
inject: true
}),
new ExtractTextPlugin("styles.css")
],
};
Here is a really bad hacky solution, and I hope someone else has a real answer / understanding of how to do this.
In your template file (index.ejs), do this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Monitor</title>
<script>
window.config = {
API_URL: "<%= htmlWebpackPlugin.options.API_URL_TEMPLATE_VAR %>"
}
</script>
</head>
<body>
<div class="container"></div>
</body>
</html>
In your webpack config, do this (the relevant part is the new HtmlWebpackPlugin where I define a variable.:
plugins: [
// Define environment variables that are accessible inside of app javascript.
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
}),
// Adds bundled file links to the index.html
new HtmlWebpackPlugin({
// The input file name
template: 'src/index.prod.ejs',
// Injects scripts into the <body>
inject: true,
// This is so hacky. I inject a string so the built .ejs file has this template var. Lets us set api_url when server is started instead of at bundle time.
API_URL_TEMPLATE_VAR: '<%= process.env.API_URL %>',
// The output file name
filename: 'index.ejs'
}),
new ExtractTextPlugin("styles.css")
],
Because I defined API_URL_TEMPLATE_VAR, when html-webpack-plugin evaluates it, it will print out <%= process.env.API_URL %> into the final template.
Hacky, but works. Not accepting my own answer / waiting for a better answer.

Related Links

Add Modules to Dependency Graph During Build
How to modify existing webpack.config.js
How to add a CSS file to index using HtmlWebpackPlugin
Choosing module format for webpack
How does webpack bundling work when I don't see the output in my project directory?
webpack importing window variable
Running webpack with watch in Bash on Ubuntu on Windows builds once and exits
eslint array-callback-return is invalid value warn is the wrong type
How do I get webpack to rewrite image sources from pug?
Programmatic Reload of webpack-dev-server
How to override plugin's main property in Aurelia/Webpack skeleton?
Webpack cannot resolve module error
How to configure webapack for returning http status code?
ERROR in Error: Child compilation failed: Cannot find module 'handlebars'
Migrate to Webpack 2 for React application
Webpack reported size is huge compared to actual output

Categories

HOME
maven
java
image
keycloak
magnific-popup
oracle11g
mockito
hashmap
framework7
google-docs
spring-jdbc
graphql
cakephp-2.5
twitter-bootstrap-4
callback
serverspec
networkx
in-app-purchase
upload
medical
python-unittest
quicklook
postgres-xl
remote-access
quickfix
try-catch
vaadin7
ghc
django-admin
saxon
transformation
undefined
connection-string
flux
google-cloud-speech
jprofiler
xlsxwriter
clickonce
restful-authentication
xpages-ssjs
qhull
tooltipster
replaceall
quote
tinymce-4
nameservers
google-cloud-endpoints-v2
http-status-code-503
create-table
titanium-mobile
contact-form
column-family
caret
html5-fullscreen
hexo
wpf-controls
overlap
io-redirection
stacked
hot-module-replacement
swift3.0.2
gesture
impersonation
greenrobot-eventbus
broadcastreceiver
nand2tetris
password-encryption
http-redirect
chain-builder
filepicker
jedis
zip4j
logparser
yii2-extension
nativeapplication
login-control
multiple-regression
hexdump
ipconfig
kendonumerictextbox
pervasive-sql
xna-4.0
cartesian-product
teamcity-8.0
kcachegrind
myo
mmc
iiviewdeckcontroller
truevault
sorl-thumbnail
network-interface
codeigniter-routing
rdtsc
preferences
issuu
jubula
xceed-datagrid
typo3-neos
oam
access-rights
web2py-modules
bulkloader
hungarian-algorithm
limejs
jelly
wsdl-2.0
path-separator
coderush
viewswitcher
objective-c-2.0
semantic-diff
hirefire
joyent
lpeg
yslow
firefox4
backcolor
ti-dsp
avatar
xetex
privilege
noscript
procedural-music
defensive-programming
multiple-languages
paul-graham

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App