我正在使用 Webpack 构建一个相当简单的网站。我正在使用
HtmlBundlerPlugin
插件附带的内置模板器来构建 HTML
页面。这个效果很好
plugins: [
new HtmlBundlerPlugin({
entry: [
{
import: './src/views/index.html', // template file
filename: 'index.html', // => dist/index.html
data: { customer_name: 'foo' }, // pass variables into template
}
],
我希望上面的值
foo
是来自 AWS SSM 参数 /bar/foo
的值。我已经编写了 JS 来检索它的值,但我只是不确定如何将两者结合在一起
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm"; //ES6+ Modules import with the command GetParameterCommand
async function get_ssm_parameter(ssm_parameter_name) {
const input = {
Name: ssm_parameter_name,
WithDecryption: true,
};
const client = new SSMClient();
const command = new GetParameterCommand(input);
const response = await client.send(command);
console.log(response)
return response
}
get_ssm_parameter("/bar/foo")
有关如何运行
JS
函数以将返回值注入 HTML 的任何帮助都很棒
您可以创建一个 webpack 插件来执行此操作。
注入-ssm-data-webpack-plugin.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
// This is your script to fetch from AWS...
const {getSsmParameter} = require("./access-ssm")
class InjectDataPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('InjectDataPlugin', (compilation) => {
const hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks.beforeEmit.tapAsync('InjectDataPlugin', (data, callback) => {
getSsmParameter("my-ssm-parameter").then((response) => {
data.html = data.html.replace('<placeholder>', response.Parameter.Value);
callback(null, data);
}).catch((error) => {
callback(error);
});
});
});
}
}
module.exports = InjectDataPlugin;
webpack.config.js
...
const InjectSSMDataPlugin = require('./inject-ssm-data-webpack-plugin');
...
module.exports = {
...
plugins: [
...
new InjectSSMDataPlugin(),
...
],
...
};
您需要确保您的本地 AWS 配置已设置,以便您的 SSM 脚本可以执行其操作,但上述插件应使用检索到的值替换您的占位符字符串。
这是一个简单的示例,它使用硬编码名称获取一个值,但您可以向插件添加一个接受参数名称的构造函数,或者更好的是:一个具有作为占位符替换文本对的键值对的对象。然后您的获取函数可以获取每个占位符所需的值并进行适当的替换。
你可以随心所欲地制作它......