我想使用HTMLWebpackPlugin来获取我的index.ejs
模板文件,插入我的打包资源,并输出一个最终的index.ejs
文件。
这个例子中有一个EJS变量<%= API_URL %>
,但是webpack正在解释它。
我如何阻止webpack替换这个变量?
开始 "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>
当你尝试运行webpack时:
ERROR in Template execution failed: ReferenceError: API_URL is not defined
期望的index.ejs结果:(已捆绑资产和EJS变量)
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")
],
};
ejs
中的if
怎么办?你将不得不将所有的逻辑放在webpack.config.js
中... - gilamranfilename: 'index.ejs'
,然后使用raw-loader
加载它,这会导致 Webpack 将文件按原样加载。 - ihodonald