By LeanCloud Weakish

Recently, the team internally needed a web gadget to upload files, and needed to write a simple front page. Gadgets like this seem too heavy to introduce React and Vue, so try Svelte, a frameless framework (which will eventually compile to JS code without a frame).

Cut to the chase and get to work. First, generate the template project:

npx degit sveltejs/template fileup
Copy the code

One of Svelte’s biggest gripes has long been its lack of support for TypeScript, but it added TypeScript support last year. Of course, with a gadget as simple as this, writing it directly in JavaScript doesn’t make much difference. But I’m still going to use TypeScript.

Unlike other template generation tools, Svelte does not officially provide a separate repository of TypeScript template projects, nor does it allow you to choose between TypeScript and JavaScript during template generation. Run a script to turn the project into a TypeScript project:

node scripts/setupTypeScript.js
Copy the code

After the transformation, perform the normal dependency installation steps to run:

npm install
npm run dev
Copy the code

Projects use NPM to manage dependencies and rollup to package them. For simple projects, you just need to change SRC/app.svelte. Templates, styles, and interaction logic are all written in one file (similar to Vue) :

<script lang="ts"> // TypeScript code </script> <style> /* CSS code */ </style> <! -- Svelte template code -->Copy the code

Start by writing the upload interface. Google it and find an off-the-shelf component called svelte file-Dropzone

npm i svelte-file-dropzone
Copy the code

Add it to a dependency, introduce it in the script section of app.svelte, and write the corresponding TypeScript code and Svelet template code:

<script lang="ts"> import Dropzone from "svelte-file-dropzone"; let files: File[] function handleFilesSelect(e) { files = e.detail.acceptedFiles } </script> <Dropzone on:drop={handleFilesSelect}>  Click to select files, or drag and drop some files here. </Dropzone>Copy the code

After you get the selected file, upload the file. Files are uploaded to LeanCloud, a BaaS cloud service that also provides file hosting services. Svelte means “slender and elegant”, which is a synonym for “lean”. In that sense, the two sounds good together.

Again, let’s add LeanCloud’s JavaScript SDK to the dependencies first:

npm i leancloud-storage
Copy the code

Then initialize the SDK:

import LC from "leancloud-storage";

const appId = "your app id";
const appKey = "your app key";
const serverURL = "https://your-custom-domain.example.com";

LC.init({
    appId,
    appKey,
    serverURL,
});
Copy the code

You can choose LeanCloud Console > Settings > Application Keys to view the appID and appKey. ServerURL is the domain name bound to LeanCloud. Of course, you need to sign up with LeanCloud and build your app first. If you do not want to bind a domain name or the domain name is not registered, you can use LeanCloud international edition.

The international version is initialized without passing the serverURL:

LC.init({
    appId,
    appKey
});
Copy the code

Uploading a file is as simple as two lines of code:

async function uploadFile(toUpload): Promise<String> {
    const uploaded = await new LC.File(toUpload.name, toUpload).save();
    return uploaded.get("url");
}
Copy the code

In the above code, after building the File with new lc.file (filename, File), call the save method to save it to the cloud, and then you can get the URL that can access the File through the URL attribute.

So far, we’ve done the core functionality of selecting and uploading files, leaving only the final step of showing the URL to the user.

{#if files} <h2>Files</h2> {#each files as file, i} {#await uploadFile(file)} <p>Uploading {file.name} ({file.size} bytes) ... </p> {:then url} <p>Uploaded: <code>{url ?? ""}</code> </p> {:catch error} <pre>{error}</pre> {/await} {/each} {/if}Copy the code

Svelte’s template syntax is used here. Presumably to save writing the parser, Svelte’s template syntax looks a little awkward (#if, /if, :catch), but despite these minor visual annoyances, it’s generally clear and readable. If is used to determine whether a file is selected, and only if a file is selected will the list of files be displayed. Then use each to traverse all the selected files and upload them. During the upload process, the name and size of the files are displayed. After the upload is complete, the URL of the files is displayed. Of course, almost every program has an error-handling component. Since this is an internal tool, the error message is displayed directly on the web page without any additional processing. Notice that we are using “await” to wait for the result from the asynchronous function that uploaded the file. When we get the result, we assign it to the URL variable, and then we can use the URL variable directly in the interface.

And there you have it, a simple upload tool in less than 50 lines of code. Looking back at the code, it’s pretty straightforward. But when you think about it, it’s amazing that just by assigning a value to the line files = e.dyail. AcceptedFiles, for example, the interface is aware of changes in files and renders different contents accordingly. This is because Svelte compiles = to setState methods in frameworks like React. Some people may think this is a little bit too magic, but in most programming languages = is pretty magic, like x = x + 1; Such a statement, just everyone is used to it.

Finally, you need to deploy it somewhere. Because it’s a purely static page, you can deploy it anywhere. Since you already use LeanCloud for file hosting, deploy your web page to LeanCloud as well.

Run the following command to compile and package the project:

npm run build
Copy the code

Then run the following command to deploy to LeanCloud:

cd public
lean switch --region CN --group web YOUR_APP_ID
lean deploy --prod 1
Copy the code

Here, CN indicates the north China node of LeanCloud, and Web indicates the name of the cloud engine group. If you use other nodes or LeanCloud international versions, or the group name is different, you need to change the value. For details, choose LeanCloud Console > Cloud Engine > Cloud Engine Group > Deployment > COMMAND Line Tool.

If you have not installed the LeanCloud cli tool, you need to install it and associate an account with it. In addition, to access pages deployed on the cloud engine, you need to either bind to a cloud engine domain name or apply for a subdomain name under avosapps.us (international edition only).

Here’s what it looks like after deployment:

As you can see, to make it easier to copy the URL, I’ve added a copy to clipboard button. Using the Svelte copy-to-Clipboard component:

npm i svelte-copy-to-clipboard
Copy the code

Just add 10 lines of code:

<script lang="ts"> import CopyToClipboard from "svelte-copy-to-clipboard"; Function handleSuccessfulCopy(I) {copyStatuses[I] = '✅'} function handleFailedCopy(I) {copyStatuses[I] = '❌'} </script> <! </h2> </h2> <! <p> At the end: <code>{url?? ""}</code> <CopyToClipboard text={url} on:copy={() => handleSuccessfulCopy(i)} on:fail={() => handleFailedCopy(i)} let:copy> <button on:click={copy}>{copyStatuses[i]}</button> </CopyToClipboard> </p> <! Slightly -- -- - > {if} /Copy the code

If you want to further improve the user experience, you can also display progress at upload time. This improvement is left to the reader as an exercise (hint).

Use LightHouse to run a score:

I didn’t think about performance when I wrote the page, but it still scored 100. There are small SEO and accessibility issues that are easy to fix and are left as exercises for the reader. Well, as you may have noticed, I’m just making excuses for my own laziness. However, if you do complete these exercises, feel free to mention PR.

So I’m almost done here, just to summarize. In terms of widgets and less interactive sites, Svelte is more straightforward to write. Compared to React and Vue, Svelte writes more concise code, has fewer Boilerplate codes, and compiles lighter code, which makes it easier for personal health (saving keyboard strokes, Avoid muscle strain) and the world (visitors load and run less code, significantly reducing carbon emissions). Frameless frameworks like Svelte and serverless cloud services like LeanCloud abstract a lot of details irrelevant to the business, enabling developers to focus on the core functions of the project, improve development efficiency and improve the development experience.

Pictured above Paul Gilmore