gpt4 book ai didi

webpack - 将HTMLWebpackPlugin与EJS文件一起使用

转载 作者:行者123 更新时间:2023-12-04 15:31:01 25 4
gpt4 key购买 nike

我想使用HTMLWebpackPlugin来获取index.ejs模板文件,插入捆绑的 Assets ,并输出最终的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 :(具有 Assets 和EJS变量)



监视器

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")
],
};

最佳答案

这是一个非常糟糕的hacky解决方案,我希望其他人对此有一个真正的答案/理解。

在您的模板文件(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-plugin对其进行评估时,它将把 <%= process.env.API_URL %>打印到最终模板中。

哈克,但行得通。不接受我自己的答案/等待更好的答案。

关于webpack - 将HTMLWebpackPlugin与EJS文件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com