如何使用webpack读取index.html中的系统环境变量



strongtextWebpack配置如下:

webpack.config.js如下所示:

const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
app: './app.js',
},
plugins: [
new CopyWebpackPlugin([
{from: '../public'},
{from: '../src/fonts', to: 'fonts'},
{from: '../src/images'}
]),
new webpack.EnvironmentPlugin(['REACT_APP_OMNITURE_URL']),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin()
],
output: {
path: path.resolve(__dirname, './build'),
filename: '[name].bundle.js',
},
module: {
rules: [
{
test: /.js$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: {presets: ["es2015", "react"]},
}],
},
{
test: /.svg$/,
exclude: [/node_modules/],
use: [{loader: 'svg-react-loader'}],
},
{
test: /.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /.(png|woff|woff2|eot|otf|ttf)$/,
loader: 'url-loader?limit=100000'
}
],
},
devServer: {
contentBase: path.resolve(__dirname, './public'),
disableHostCheck: true,
historyApiFallback: true
},
};

我需要实现的是读取index.html中的REACT_APP_OMNITURE_URL环境变量,如下所示:

<script type="text/javascript" src="//%REACT_APP_OMNITURE_URL%/analytics.js"></script>

在这方面有什么帮助吗?

此外,我们使用Bamboo根据环境变量动态传递给我们。我们如何将这些变量分配给节点变量并在插件中使用

您可以使用插值html插件

yarn add interpolate-html-plugin --dev

webpack.config.js

plugins: [
new InterpolateHtmlPlugin({
'REACT_APP_OMNITURE_URL': process.env.REACT_APP_OMNITURE_URL
})
]

然后在html文件中,您可以使用它。

index.html

<script type="text/javascript" src="//%REACT_APP_OMNITURE_URL%/analytics.js"></script>

更多信息可以在这里找到:https://www.npmjs.com/package/interpolate-html-plugin

你试过html webpack插件吗?添加脚本路径对我很有用。来自文档:

webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin()
]
}
This will generate a file dist/index.html containing the following
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>

最新更新