icons.js 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-var-requires */

const path = require('path');
const {promises: fs} = require('fs');
const {default: svgr} = require('@svgr/core');
const babel = require('@babel/core');
const {camelCase} = require('lodash');
const {ensureDir} = require('fs-extra');

const root = path.resolve(__dirname, '../public/icons');
const pathname = '/icons';
const dist = path.resolve(__dirname, '../dist');
const dest = path.join(dist, pathname);

async function transform(file, minified) {
    const basename = path.basename(file, '.svg');
    let jsx = await svgr(
        await fs.readFile(file, 'utf-8'),
        {
            icon: true,
            svgProps: {
                fill: 'currentColor',
                className: 'vdl-icon'
            }
        },
        {componentName: camelCase(basename).replace(/./, w => w.toUpperCase())}
    );
    jsx = jsx.replace('import * as React from "react";', 'import React from "../web_modules/react.js";');
    const result = await babel.transformAsync(jsx, {
        filename: basename + '.jsx',
        presets: ['@babel/preset-react'],
        minified
    });
    return result.code;
}

async function build() {
    await ensureDir(dest);
    const files = await fs.readdir(root);
    for (const file of files) {
        if (path.extname(file) === '.svg') {
            const js = await transform(path.join(root, file), false);
            await fs.writeFile(path.join(dest, path.basename(file, '.svg') + '.js'), js, 'utf-8');
        }
    }
    console.log('Icons copied!');
}

if (require.main === module) {
    build();
}

const middleware = () => {
    return async (req, res) => {
        const file = path.join(root, req.path.replace(/\.js$/, '.svg'));
        if ((await fs.stat(file)).isFile()) {
            res.type('js');
            res.send(await transform(file, false));
        }
    };
};

module.exports = {
    middleware,
    root,
    pathname
};