webpack的html模板中插入变量写法
vue-cli文档中的描述如下
Index 文件#
public/index.html
文件是一个会被 html-webpack-plugin 处理的模板。在构建过程中,资源链接会被自动注入。另外,Vue CLI 也会自动注入 resource hint (preload/prefetch
、manifest 和图标链接 (当用到 PWA 插件时) 以及构建过程中处理的 JavaScript 和 CSS 文件的资源链接。
插值#
因为 index 文件被用作模板,所以你可以使用 lodash template 语法插入内容:
<%= VALUE %>
用来做不转义插值;<%- VALUE %>
用来做 HTML 转义插值;<% expression %>
用来描述 JavaScript 流程控制。
除了被 html-webpack-plugin
暴露的默认值之外,所有客户端环境变量也可以直接使用。例如,BASE_URL
的用法:
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
更多内容可以查阅:
1. html可以插入那些变量
1.1 htmlWebpackPlugin本身的变量
htmlWebpackPlugin.options
htmlWebpackPlugin.tags
htmlWebpackPlugin.files
1.2 webpack的对象
webpackConfig对象
compilation对象
The following variables are available in the template by default (you can extend them using the templateParameters
option):
-
htmlWebpackPlugin
: data specific to this plugin-
htmlWebpackPlugin.options
: the options hash that was passed to the plugin. In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through to your template. -
htmlWebpackPlugin.tags
: the preparedheadTags
andbodyTags
Array to render the<base>
,<meta>
,<script>
and<link>
tags. Can be used directly in templates and literals. For example:<html> <head> <%= htmlWebpackPlugin.tags.headTags %> </head> <body> <%= htmlWebpackPlugin.tags.bodyTags %> </body> </html>
-
htmlWebpackPlugin.files
: direct access to the files used during the compilation.publicPath: string; js: string[]; css: string[]; manifest?: string; favicon?: string;
-
-
webpackConfig
: the webpack configuration that was used for this compilation. This can be used, for example, to get thepublicPath
(webpackConfig.output.publicPath
). -
compilation
: the webpack compilation object. This can be used, for example, to get the contents of processed assets and inline them directly in the page, throughcompilation.assets[...].source()
(see the inline template example).
详细可参考 html-webpack-plugin模板文档 和 模板变量examples
2. 区分开发环境和生产环境的变量写法
在 html 标签里面这样使用
<% if (process.env.NODE_ENV === 'development') { %> <script src="<%= BASE_URL %>libs/vue/vue.js"></script> <% } else { %> <script src="<%= BASE_URL %>libs/vue/vue.min.js"></script> <% } %>
在 script 脚本里面这样使用
<script> if ('<%= process.env.NODE_ENV %>' === 'development') { window.SITE_CONFIG['apiURL'] = '/api'; } else { window.SITE_CONFIG['apiURL'] = '/prod_api'; } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-11-22 git用户名和邮箱配置