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

undefined:1 SyntaxError: Unexpected token in Laravel 5.4 and Vuejs
Source maps not generated with simple webpack config
How to config babel-loader to make output code compatible with ie >= 9 in webpack 2?
creating a less bundle with webpack
Trying to concatenate js files with webpack (like a gulp script)
Webpack Configuring CommonsChunkPlugin
Use htmlwebpackplugin.files as a JSON
How to Build Vue project with vue-cli 'npm run build' command that will contain relative reference in such tags as 'img', 'script' 'link' and others?
Destructuring assignment not working in IE 11 even after using babel plugins
How to include css files in Vue 2
Vuejs webpack static folder not working in subfolder
How to use aurelia cli some features in skeleton-typescript-webpack?
Minification for ES6 code in webpack using babel
Karma “request.replace is not a function” error
how to extract vue files style into one seperate style.css file
Webpack and svgstore, how?

Categories

HOME
ibm-bluemix
sendgrid
wso2
plot
stock
yahoo-oauth
leon
amazon-ecs
dxl
survey
retrofit
azure-media-services
dacpac
spring-kafka
izpack
task
lombok
django-simple-history
libtiff
after-effects
ab-testing
visual-composer
swingx
riot.js
arabic
dcevm
zurb-foundation-6
blazemeter
user-interaction
log4js-node
atlassian-crucible
webkitspeechrecognition
flink-streaming
scorm2004
openoffice.org
gammu
http-digest
jquery-bootgrid
event-driven
libvpx
occlusion
unspecified
xenforo
splice
eclipse-scout
spring-security-kerberos
bootstrap-dialog
eclipse-gef
convertapi
flickr-api
scrollable
upstart
django-scheduler
vtigercrm
eventkit
django-debug-toolbar
storekit
gridview-sorting
spim
intel-fortran
content-length
interrupted-exception
sniffer
sonarqube5.1.2
geonetwork
offloading
jsonpickle
nstableviewcell
internet-connection
has-many-through
wp-query
doskey
xceed-datagrid
mechanize-ruby
hyprlinkr
google-cloud-save
dataservice
delphi-6
broken-links
frameset
windows-phone-7.1.1
amazon-appstore
pendrive
fireworks
yetanotherforum
recent-documents
web-application-design
sproutcore-2
dentrix
multi-tier
photoshop-cs4
project-hosting
ubuntu-9.04
.net-1.0
commodore
signal-handling

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