Electron常见问题 常用路径/静态资源丢失

 

本文主要是描述electron中路径相关的问题

  • 静态资源丢失的原因
  • 静态资源路径一致性处理方案-resolvePath
  • 常用路径---userPath/appData/文档
  • pathUtil的封装

一、静态资源丢失的原因

Electron常见问题(二)Electron图标打包我们讨论过静态资源的打包,但有时候我们会碰到在local环境运行程序的时候静态资源可以看到,但是build成产品后静态资源丢失的情况。
这里用托盘图标举例。
托盘图标的静态资源我们通过extraResources复制操作放到打包后的文件中

package.json
{
    ...  
    "build": {
      ...
      "extraResources": [
        {
          "from": "icons/", 
          "to": "icons/"
        } // 可以移动多个文件夹,from-to
      ],  
      ...
    },
    ...
}

打包后的icons会复制到文件的resources中

 
 

local环境中我们引入图标使用相对路径来引入图标

const iconName =process.platform === 'win32' ?
 'icons/windows-icon.png' : 'icons/iconTemplate.png';
const ningImage = nativeImage.createFromPath(iconName);
tray = new Tray(ningImage);

我们的主代码会被打包在app.asar中

主代码打包位置

对于主代码来说,图标的位置在 'icons/windows-icon.png' 没有错。

但在local环境我们的主代码在app/main.developments.ts中,这样 'icons/windows-icon.png' 是找不到对应的icon的。

 
 

二、 静态资源路径一致性处理方案-resolvePath

为了解决路径不一致的情况,我们可以封装一个resolvePath类,将local环境的路径和产品环境的路径相一致。

export default class PathUtils {
    // 将startPath作为标准路径,静态资源的路径和项目中使用到的路径全部由startPath起始
    public static startPath = path.join(__dirname, '..');

    public static resolvePath = (dirPath) => {
        return path.join(PathUtils.startPath, dirPath || '.');
    };
}

这样,相应的tray图标引入方式改为

const iconName =
        process.platform === 'win32'
            ? PathUtils.resolvePath('icons/windows-icon.png')
            : PathUtils.resolvePath('icons/iconTemplate.png');
    const ningImage = nativeImage.createFromPath(iconName);

    tray = new Tray(ningImage);

三、常用路径---userPath/appData/文档

我们系统的配置文件通常放到用户目录下,如 C://User/Administrator/xxxconfig.json 中,这个路径一般称为userProfile,但是这是初始的情况,有的用户系统盘放在D盘E盘等其他盘,这时对应的用户目录位置也会改变。
所以我们的用户目录一般使用userProfile来获取,这个变量在electron的环境变量中也是可以找到的。

process.env['USERPROFILE'];

同样的用户的缓存目录APPDATA路径为

process.env['APPDATA']

还有一个常用路径是文档,我们熟知的qq,微信等接受到的文件一般都会缓存在这个位置。

 
 
常用路径文档库

而文档的位置在electron中是找不到的,而且文档映射的路径也是可以手动编辑的。
但它最终是存在注册表中的。所以我们需要花些手段去读取注册表。
好在网上可以找到regedit组件可以让nodejs访问注册表。
接下来我们只要找到文档对应的位置就可以了。

 
 
注册表中的文档位置

四、pathUtil的封装

增加了userPath/appData/文档路径,我们的pathUtil也要进行升级,如下

export default class PathUtils {
    public static startPath = path.join(__dirname, '..');

    public static userPath = process.env['USERPROFILE'];

    public static userDocPath;

    public static appdataPath = process.env['APPDATA'];

    public static resolvePath = (dirPath) => {
        return path.join(PathUtils.startPath, dirPath || '.');
    };

    public static resolveUserPath = (dirPath) => {
        return path.join(PathUtils.userPath, dirPath || '.');
    };

    public static resolveUserDocPath = (dirPath) => {
        return new Promise((resolve, reject) => {
            getUserDoc().then((docPath: string) => {
                PathUtils.userDocPath = docPath;
                resolve(PathUtils.userDocPath);
            });
        });
    };
}

const getUserDoc = () => {
    return new Promise((resolve, reject) => {
        const regedit = require('regedit');
        regedit.setExternalVBSLocation(PathUtils.resolvePath('vbs'));

        const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders';
        regedit.list(key, function(err, result) {
            if (err) {
                console.error('Window Reg:', err);
            } else {
                try {
                    resolve(result[key].values['Personal'].value);
                } catch (e) {
                    const docPath = path.join(PathUtils.userPath, 'Documents');
                    if (!fs.existsSync(docPath)) {
                        fs.mkdirSync(docPath);
                    }
                    resolve(docPath);
                }
            }
        });
    });
};

 

 
 
原文地址:https://www.cnblogs.com/onesea/p/15270790.html