react 打包env变量输出html
JS脚本 2023/10/13 21:33:13 点击:不统计
转载%77%77%77请%2E%66%6F%72%61%73%70%2E%63%6E注明
第一次使用react,学习 加载.env变量到 html 输出,并将文件打包复制到 static。
1. json文件,文件目录参考下面
.env 中配置
JS_NAME="forasp.js"
2. 增加打包配置
在webpack.config.js 中,增加下面,让系统打包 调用.env 配置。
# 加载.env
require('dotenv').config();
# 组织路径,__dirname 标示当前 webpack.config.js 目录
const appPath = path.join(__dirname, "client", "app");
# 上面实际路径为 ./client/app
# 判断 加载参数 WEB_LANGUAGE值,返回对应文件名称
const js_file = process.env.JS_NAME ?;
在 plugins 中增加 下面配置, 三个点是固定前缀,后面标示上面引入的json 数组内容
HtmlWebpackPlugin({
"js_file":js_file
}),
3. 设置文件复制到打包根目录 static
const config 中 output
output:
{
publicPath:"/static/"
}
在 plugins 中增加 下面配置,将当前js 文件打包直接复制到,打包后的 static 目录下
new CopyWebpackPlugin([
{ from: `@/${js_file}` },
])
4. 在html中输出内容, 下面输出 “菜单” 注意WL 与 json 的key 一致。
<script src="/static/<%= htmlWebpackPlugin.options.WL.menu %>"></script>
原载于:本文原载于www.forasp.cn