强文本 Webpack的配置如下:
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来根据环境变量动态地传递给我们。我们如何将这些变量分配给节点变量并在插件中使用?
答案 0 :(得分:1)
您可以使用interpolate-html-plugin
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
答案 1 :(得分:0)
您尝试过html-webpack-plugin吗?这对我添加脚本路径很有用。从文档中:
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>