"Strve.js" is a JS library that can convert strings into views

preface

I haven't written original for a long time. Today I'll send an article about my own JS Library - Strve.js.

Finally, I experienced the fun of writing my own JS library or framework, my own documents and tools.

If you want to know about Strve.js, you can start according to the document.

Official documents:

https://www.maomin.club/site/strvejs/

NPM:

https://www.npmjs.com/package/strvejs

Github:

https://github.com/maomincoding/strve

Strve.js

A JS library that can convert strings into views.

  • ⚡ Quickly

Super fast virtual DOM.

  • 📦 Small space

The size of the source code file is only 4kb.

  • 🗂 Flexibly

Easy and flexible disassembly of different code blocks.

introduce

Strve.js is a JS library that can convert strings into views. The string here refers to the template string, so you only need to develop the view in JavaScript. Strve.js is not only easy to use, but also convenient for flexible disassembly and assembly of different code blocks.

If you want to start the project, please see how to install it below!

install

CDN

If you use native ES Modules.

<script type="module">
  import { Strve, render, updateView } from 'https://cdn.jsdelivr.net/npm/strvejs/dist/strve.esm.min.js';
</script>

NPM

npm i strvejs

Command line tools

Create strve is a project building tool based on strve.js. You can use it to build pages more conveniently and flexibly.

Global installation

npm install create-strve -g

View version

create-strve -v

Initialize project

create-strve init <projectName>

Get started quickly

The easiest way to try Strve.js is to use the direct import CDN link. You can open it in the browser and follow the examples to learn some basic usage.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Strve.js</title>
</head>

<body>
    <div id="app"></div>
    <script type="module">
        import { Strve, render, updateView } from 'https://cdn.jsdelivr.net/npm/strvejs/dist/strve.esm.min.js';

        const state = {
            arr: ['1', '2'],
        };

        function App() {
            return render`
              <div class='inner'>
                  <button id='btn2' onclick=${usePush}>push</button>
                  <ul>
                    ${state.arr.map((todo) => render`<li key=${todo}>${todo}</li>`)}
                  </ul>
              </div>
          `;
        }

        function usePush() {
            updateView(() => {
                state.arr.push('3');
            });
        }

        Strve('#app', {
            data: { state },
            template: App
        });
    </script>
</body>

</html>

If you want to learn more about Strve.js, you can read on.

use

API

Strve.js currently has only three API s.

  • Strve
  • render
  • updateView

Isn't it very simple! Let's see what these three API s mean? How do you use them?

Strve

  • Parameters:
    • string
    • object
  • Details:

Initialize Strve.js. The first parameter passes in the name of the node selector that needs to be mounted to the HTML page. The second parameter is passed into an object. The first attribute data represents the state object, and the second attribute template represents the template function.

Strve('#app', {
    data: { state },
    template: App
});

render

  • Type: Function
  • Details:

render ` ` is a label function. The syntax of the label function is to take a template string directly after the function name, and obtain parameters from the interpolation expression in the template string. For example, you can write HTML tags directly in the template string.

function App() {
    return render`
        <div class='inner'>
            <h1>Hello</h1>
        </div >
    `;
}

updateView

  • Parameters:
    • Function
  • Details:

It has only one parameter, which is a function. In the function body, you need to execute a value that will change the page state, such as state.msg in the following example.

const state = {
    msg:'1'
};

function App() {
    return render`
        <div class='inner'>
            <button onclick=${useChange}>change</button>
            <p>{state.msg}</p>
        }
        </div >
    `;
}

function useChange() {
    updateView(() => {
        state.msg = '2';
    });
}

interpolation

Strve.js uses a JavaScript based template string syntax that allows developers to declaratively bind the DOM to the data of the underlying instance. All template strings of strve.js are legal HTML, so they can be parsed by standard browsers and HTML parsers.

In the underlying implementation, Strve.js compiles the template string into a virtual DOM rendering function and minimizes the number of DOM operations.

In Strve.js, you can enjoy using JavaScript Template Strings and feel its unique charm!

text

The most common form of data binding is text interpolation using the symbol ${}:

const state = {
    msg: 'hello'
};

function App() {
    return render`
        <div class='inner'>
            <p>${state.msg}</p>
        </div >
    `;
}

In addition, you can also use a simpler method to sign {}, which can also achieve the desired effect.

const state = {
    msg: 'hello'
};

function App() {
    return render`
        <div class='inner'>
            <p>{state.msg}</p>
        </div >
    `;
}

However, when using this symbol {}, it should be noted that it is only applicable to text interpolation within the label. For example, in this case, it doesn't work, but you can use the powerful symbol ${}.

// Bad
function App() {
    return render`
        <div class='inner'>
            <input type="text" value={state.msg}/>
        }
        </div >
    `;
}

// Good
function App() {
    return render`
        <div class='inner'>
            <input type="text" value=${state.msg}/>
        }
        </div >
    `;
}

expression

Currently, only expressions in the symbol ${} are supported. For example,

const state = {
    a: 1,
    b: 2
};

function App() {
    return render`
        <div class='inner'>
            <p>${String(state.a + state.b)}</p>
        }
        </div >
    `;
}

Property binding

Earlier, we can see that using the symbol ${} can bind a value to the attribute value.

function App() {
    return render`
        <div class='inner'>
            <input type="text" value=${state.msg}/>
        }
        </div >
    `;
}

In addition, you can bind other properties, such as class.

const state = {
    isRed: true
};

function App() {
    return render`
    <div class='inner'>
        <p class=${state.isRed ? 'red' : ''}>Strve.js</p>
    </div >
`;
}

conditional rendering

We can also use the symbol ${}, which will only be rendered when the expression of the instruction returns the true value.

const state = {
    isShow: false
};

function App() {
    return render`
        <div class='inner'>
            <button onclick=${useShow}>show</button>
            ${state.isShow ? render`<p>Strve.js</p>` : ''
        }
        </div >
    `;
}

function useShow() {
    updateView(() => {
        state.isShow = !state.isShow;
    });
}

List rendering

We can render a list based on an array with the symbol ${}. For example, we use the map method of array to render the list, and we can dynamically add array items.

const state = {
    arr: ['1', '2']
};

function App() {
    return render`
        <div class='inner'>
            <button onclick=${usePush}>push</button>
            <ul>
            ${state.arr.map((todo) => render`<li key=${todo}>${todo}</li>`)}
            </ul>
        }
        </div >
    `;
}

function usePush() {
    updateView(() => {
        state.arr.push('3');
    });
}

event processing

We can use the native onclick instruction to listen for DOM events and execute some JavaScript when the event is triggered. You need to use the symbol ${} to bind events.

function App() {
    return render`
        <div class='inner'>
            <button onclick=${useClick}>sayHello</button>
        }
        </div >
    `;
}

function useClick() {
    console.log('hello');
}

With Vue.js

Strve.js can be used not only alone, but also with Vue.js. You need to be called the Strve() registration method after the Vue instance is mounted, and the first parameter already exists in the template tag.

App.vue

<template>
  <div id="container">
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld ,{hello} from './components/HelloWorld.vue';
import { about,state } from './components/About.vue';
import { render, Strve } from "strvejs";
const AppTm = () => render`
      <div>
        ${hello()}
        ${about()}
      </div>
`;
export default {
  name: "App",
  components:{
    HelloWorld
  },
  mounted() {
    Strve("#container", {
      data: {state},
      template: AppTm,
    });
  },
};
</script>

If you need to share a method with Vue, it is recommended to use it in the setup method.

HelloWorld.vue

<template>
  <div>
    <img src="../assets/logo.png" alt="" @click="useCliimg">
  </div>
</template>
<script>
import { render } from "strvejs";
import styles from '../assets/hello/hello.module.css';

export const hello = ()=>render`
<h2 class="${styles.color}" onclick=${useCliimg}>hello</h2>
`
function useCliimg(){
    console.log(1);
}

export default {
  name:'HelloWorld',
  setup(){
    return {
      useCliimg
    }
  }
}
</script>

If you want to fully use Strve.js in Vue components, of course. Finally, however, it is recommended to use export default to export the component name.

About.vue

<script>
import { render, updateView } from "strvejs";
import styles from '../assets/about/about.module.css';

export const about = ()=>render`
<div>
    <p>{state.msg}</p>
   <h2 class="${styles.color}" onclick=${useClick}>about</h2>
</div>
`
export const state = {
    msg:"hello"
}

function useClick() {
    updateView(()=>{
        state.msg = 'world';
    })
}
export default {
    name:"About"
}
</script>

Match with React.js

Compared with Vue.js, Strve.js is more flexible to use with React.js. It is also necessary to call the Strve() method registration method after the component is first rendered.

App.js

import {useEffect} from 'react'
import {Strve,render,updateView} from 'strvejs';
import './App.css';

const state = {
  msg:"Hello"
}

function Home(){
  return render`<h1 onclick=${useClick}>{state.msg}</h1>`
}

function useClick(){
  updateView(()=>{
    state.msg = "World";
  })
}

function App() {
  useEffect(()=>{
    Strve(".App",{
      data:{state},
      template: Home
    })
  })
  return (<div className="App"></div>);
}

export default App;

tool

create-strve

We also briefly introduced that create strve is a project construction tool based on Strve.js. You can use it to build pages more conveniently and flexibly. Create strve is built with Vite. It is a new front-end construction tool, which can significantly improve the front-end development experience.

install

Global installation

npm install create-strve -g

View version

create-strve -v

Initialize project

create-strve init <projectName>

start-up

yarn dev
# OR
npm run dev

deploy

yarn build
# OR
npm run build

to configure

Because create strve is built with Vite, you can customize the configuration of create strve according to Vite's convention configuration.

Posted by rage2021 on Wed, 01 Dec 2021 02:07:39 -0800