У меня есть HTML проект с элементами React (передача тегов сценария реакции в html), и мне нужно защитить ключ API в сценарии с помощью URL-адреса карты Google. Я новичок в этом, и я не уверен, возможно ли это вообще? Я пробовал 'dotenv'
и 'dotenv webpack'
.
В результате: я могу получить доступ к своему API-ключу, определенному в .env, но только в терминале, запустив $ node -r dotenv/config ./src/index.js
// ./src/index.js
console.log(process.env.API_KEY)
Я пытался сохранить его в переменной и вставить новый тег сценария в HTML, например, так:
// ./src/index.js
require('dotenv-webpack');
var newScript = document.createElement("script");
newScript.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.S3_API}&libraries=places`;
newScript.type = "text/javascript";
target.appendChild(newScript);
Я получаю Uncaught ReferenceError: require is not defined at index.js
Я также пытался HtmlWebpackPlugin
:
// ./webpack.config.js
const Dotenv = require('dotenv-webpack');
const path = require('path');
module.exports = {
plugins: [
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true
}), // load .env.example (defaults to "false" which does not use dotenv-safe))
new HtmlWebpackPlugin({
template: './web/web.html',
title: 'Custom template using html-loader',
environment: {
'GOOGLE_PLACES_API': process.env.GOOGLE_PLACES_API;
})
]
};
<!-- ./web/web.html -->
...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<%= htmlWebpackPlugin.options.environment %>&libraries=places"></script>
...
Буду признателен за любую помощь или предложения