我想使用 HTMLWebpackPlugin 来获取我的index.ejs
模板文件,插入我的捆绑资产,并输出一个最终index.ejs
文件。
这个例子有一个 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")
],
};