我遇到了问题。我想在浏览器中访问一些env变种。
我是这样做的:
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.end.NODE_ENV),
'API_URL': JSON.stringify(process.env.API_URL)
})
这工作得很好,但它在构建时运行,我需要在运行时更改变量。
我有一个简单的快速服务器来运行我的应用程序。为了做我需要的,这是我的解决方案:
const Transform = require('stream').Transform;
const parser = new Transform();
parser._transform = function(data, encoding, done) {
const str = data.toString().replace('<head>', `<head>
<script>
const API_URL = "${process.env.API_URL}"
const NODE_ENV = "${process.env.NODE_ENV}"
</script>`);
this.push(str);
done();
};
if (fs.existsSync(DIST_DIR)) {
app.use(express.static(DIST_DIR))
app.get("*", (req, res) => {
res.write('<!-- Begin stream -->\n');
fs.createReadStream(HTML_FILE)
.pipe(parser)
.on('end', () => {
res.write('\n<!-- End stream -->')
})
.pipe(res);
})
app.listen(process.env.PORT || 3000, '0.0.0.0', () => {
console.log('Listening on port %d', process.env.PORT || 3000);
})
} else {
throw new Error ("No build was found in the ../dist folder. Please run 'npm run build'.")
}
我基本上在服务时动态更改我的index.html文件。感觉这是不好的做法,但同时它运作良好。
你们怎么看待它?有更好的方法吗?