使用带有EJS文件的HTMLWebpackPlugin
问题描述:
我想使用HTMLWebpackPlugin获取我的index.ejs
模板文件,插入捆绑的资产并输出最终的index.ejs
文件。使用带有EJS文件的HTMLWebpackPlugin
这个例子有一个EJS变量<%= API_URL %>
,但webpack正在解释它。
如何停止webpack来代替变量?
启动 “模板”:
<!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>
当您尝试的WebPack运行:
ERROR in Template execution failed: ReferenceError: API_URL is not defined
期望的结果index.ejs:(已捆绑资产和EJS VAR )
监视器 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")
],
};
答
这是一个非常糟糕的哈克索尔我希望别人对如何做到这一点有真正的答案/理解。
在模板文件(index.ejs),这样做:
<!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>
在你的WebPack配置,这样做(相关部分是新HtmlWebpackPlugin,我定义一个变量:
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")
],
因为我定义API_URL_TEMPLATE_VAR
,当HTML的WebPack-插件计算它,它会打印出<%= process.env.API_URL %>
到最终模板。
哈克,但WOR KS。不接受我自己的答案/等待更好的答案。
答
我遇到同样的问题,并增加一个引号(“)的变量的定义解决了这个问题:
你的情况:
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'API_URL': '"' + JSON.stringify(process.env.API_URL) + '"'
}
})
...