Creating a package for Svelte

Intro

The idea of the following post is to make a quick, practical and simple version of how to create a package that can be downloaded via npm in our project made with Svelte.

I recently finished my first package and the truth is that, although the information on the web is quite complete, the idea is to transmit my process in a short and simple way, and I didn't find too many posts explaining how to leave the package working for Svelte.

1. 🛠️ Pre requisites

First of all, the following is required:

  1. Have an account on GitHub
  2. Account at npm
  3. Have Node, npm and GIT installed on your computer.

That's it, we can go on.

2. 💡 The idea

Before you start anything, it's good to have an idea of what you want to do, so that you don't waste time and steps doing and undoing the package. No matter how basic it is, think of something that you can use first, both to use and to practice, and that you would like to upload.

And don't think if it's already done or not, most things are probably already done, just look for the spin on it to have an added value for you.

3. 🏁 Start the package

You can now create a folder on your pc, with the name of the package (or the one you like), and open your preferred editor.

In my case I used Visual Studio Code, which already has a built-in terminal, in case you use another one, you should open the Node console and go to the directory you just created.

Now they must run npm init -y

This will create a package.json file to place information about the package, such as name, author, description, the dependencies it uses, the version etc.

    {
      "name": "",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }

You can fill in the fields like name, description, keywords, author and license

Now we can install the dependencies that will use our package. Note that this is a basic code, this means that we will install basic dependencies.

Execute in your terminal the following command

npm install -D rollup rollup-plugin-node-resolve rollup-plugin-svelte svelte

This will install the basic dependencies like devDependencies (-D), so they will only be used for development.

The package.json will add the following field:

    "devDependencies": {
        "rollup": "^1.28.0",
        "rollup-plugin-node-resolve": "^5.2.0",
        "rollup-plugin-svelte": "^5.1.1",
        "svelte": "^3.16.7"
    }

4. 📦 The package

Now we are going to create a folder src in the root of the directory, and inside a file index.js

Inside this file we will put the following code:

    import Name from './Name.svelte';

    export default Name;

Where Name should be the name you want to give the component.

And then, we will also create inside the folder src, a file Name.svelte where Name should be the same that they put in the file index.js

Once inside the .svelte file, it's up to you to build the component of the idea you came up with, here it only acts as a normal .svelte page, with the style script blocks and the html.

You can import elements of Svelte without problems.

package.json

We're going to make some changes to this file, adding the following:

    "main": "dist/index.js",
    "module": "dist/index.mjs",
    "svelte": "src/index.js",
    "scripts": {
        "build": "rollup -c",
        "dev": "rollup -c -w"
    },
  • In main we will set the output after running the build script (no need to create the /dist directory, it will be created automatically)
  • In module we are going to define the same thing but as output a .mjs, file so that Node can distinguish between modules created with CommonJS and ES6. More info here
  • In svelte, we will define the path of our index.js file created earlier.
  • And then we'll define the scripts (if you're familiar with Svelte, you'll know them).

rollup.config.js

We're going to create another file, but this time at the root level (where the src folder is, and the package.json), and we're going to call it rollup.config.js

If you've used Svelte before, you already know this file.

We're going to run this file when we run the build script and pass it some directives on what to do:

    import svelte from 'rollup-plugin-svelte';
    import resolve from 'rollup-plugin-node-resolve';

    const pkg = require('./package.json');

    export default {
        input: 'src/Name.svelte',
        output: [
            { file: pkg.module, 'format': 'en' },
            { file: pkg.main, 'format': 'umd', name: 'Name' }
        ],
        plugins: [
            svelte(),
            resolve()
        ],
    };
  • In the first 2 lines, we exported 2 of the units that we installed before.
  • Then in the constant pkg, we bring the package.json
  • And then we tell him that the input he will enter is the .svelte file (again changing Name by the name of his file), and that the output will be pkg.module, that is the module value we put before in the package.json "module": "dist/index.mjs" and the main "main": "dist/index.js", changing also the 'Name' value by that of his component.
  • And then we execute the 2 plugins.

5. 🧪 Test locally

There is a way to test our package locally, before uploading it to npm.

Create a new folder on your computer and install Svelte.

  1. From the terminal, in your package's directory, run the command npm link
  2. From the newly created folder where we installed Svelte in step 1, open a new terminal located in that directory and run the command npm link /path/of/your-package.

This will allow us to test the package locally, and also if we make any modifications to it, there is no need to update or install each time, it updates itself.

6. 🚀 Publish in npm

After all this, we are ready to release the package and make it available for installation via npm.

It is recommended to have created in the root directory a file README.md with information about our package. How to install it, how to use it, configurations, etc.

This is a good example for you to use.

Remember that the README.md will be the same for npm as for the GitHub repository.

Publish

  1. Execute in the terminal, in the directory of our package, the command npm adduser, it will ask for the credentials of our account.
  2. Then run npm publish and that's it!

IMPORTANT: Any changes we make to our package, before we can run npm publish again, we must change the version in our package.json.

    "version": "1.0.0"

7. 🚀 Posting on GitHub

To get the package into our GitHub repository, let's do the following:

  1. Create a .gitignore file in the root directory of your package that includes the following:
        # Directories
        node_modules/
        dist/

This prevents the dist folder and the node_modules folder from being published.

  1. In our GitHub account, we create a repository with the name of our package, and we put that DO NOT create a README.md file
  2. We execute the following commands in our terminal:
       git init
        git remote add origin https://github.com/tu-usuario/el-nombre-del-repositorio.git
        git add .
        git commit -m "First Commit"
        git push -u origin master

This will upload our files to the repository (except the ones we put in the .gitignore file)

🧐 Recommendations

It is quite useful, once our repository is created and our package is published, to add the following lines in our package.json file:

        "repository": {
            "type": "git",
            "url": "https://github.com/tu-usuario/el-nombre-del-repositorio"
        },
        "homepage": ""
        "bugs": {
            "url": "https://github.com/tu-usuario/el-nombre-del-repositorio/issues"
        }

This will also add on the npm page of our package, the Homepage and Repository fields linking directly to our package site and the GitHub repository.

📕 Conclusion

Is there much more that can be done before publishing the package? Yes, you can, like run tests, have a LICENSE file, add prebuild and pre-publish scripts in package.json, etc.

Yes, you can, but the idea of the post is that at least they know how to start, then it's up to each one to add more things to the process.

I hope everything is understood, if you can't comment below 😀

Greetings!

Photo by Clark Tibbs on Unsplash

No Comments Yet