uniapp打包h5后自定义配置文件可修改 的操作方法

2,565 阅读1分钟

1.在根目录下创建static目录下,然后创建configs.js

image.png

configs.js内容如下:

 const configs = {
   baseUrl:"xxx"
 }

2.在manifest.jsonh5下设置"template" : "template.h5.html

image.png

3.在项目根目录下新建 template.h5.html 文件。

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <script>
            var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
            document.write('<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />')
        </script>
		<script src="./static/configs.js"></script>
        <link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
    </head>
    <body>
        <noscript>
            <strong>Please enable JavaScript to continue.</strong>
        </noscript>
        <div id="app"></div>
        <!-- built files will be auto injected -->
    </body>
</html>

4.使用时,在页面上直接使用configs.js的变量就可以了,例在main.js使用

if ('/h5/' === window.location.pathname) {
    // 在首页获取到全局变量存入缓存
    uni.setStorageSync('config', configs)
}

5.打包成H5后,直接修改static中的文件中的configs.js即可,无需重复打包。

image.png

公共配置js:

// 从缓存获取配置
var config = uni.getStorageSync('config');
if ('/h5/' === window.location.pathname && !config) {
    // 如果在首页且缓存无数据,直接用全局变量
    config = configs;
}
if ('/h5/' !== window.location.host && !config) {
    // 如果不在首页且缓存无数据,跳转首页设置缓存
    const url = window.location.href.split('/h5/')
    window.location.href = url[0] + '/h5/'
}
export default config;

参考链接:blog.csdn.net/wang_J_8799…