I am trying to assign variable inside <script>
tag by means of html-webpack-plugin where the variable is located. I can easily use it inside html tags like title <%= htmlWebpackPlugin.options.applicationId %>
My html-webpack-plugin looks like :
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
applicationId : process.env.APPLICATION_ID ?process.env.APPLICATION_ID : 1,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: false
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
And I want to use variable applicationId on index.html page with following script :
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.write(xhr.responseText);
}
};
var appId = <%= htmlWebpackPlugin.options.applicationId %>;
xhr.open("GET","https://somesite.com/NavigationApi/api/content/get?applicationId=" + appId,false);
xhr.send(null);
</script>
您可以设置一个隐藏的输入并在其中设置appId
,然后可以使用javascript检索该值(如果要使用普通JS,请确保在jquery的onload
事件中执行此操作,或者使用DOMContentLoaded进行此操作),希望对您有所帮助。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.