<Mazipan />

Migrate Nuxt to TypeScript

Available in other languages: Bahasa Indonesia

Story telling about the steps that I worked on when migrating the Nuxt project from using vanilla JavaScript to using TypeScript

As we all know that the default from the Nuxt project will be to create a code based on JavaScript Vanilla. Whereas the increasingly widespread use of TypeScript among JavaScript developers makes me personally interested in implementing the use of TypeScript on my open source code project.

Quran Offline
Quran Offline

The following are the things I worked on in the migration process:

Adding tsconfig.json

1{
2 "compilerOptions": {
3 "target": "es5",
4 "module": "esnext",
5 "moduleResolution": "node",
6 "lib": ["esnext", "esnext.asynciterable", "dom"],
7 "esModuleInterop": true,
8 "experimentalDecorators": true,
9 "resolveJsonModule": true,
10 "allowJs": true,
11 "sourceMap": true,
12 "strict": true,
13 "noImplicitAny": false,
14 "strictNullChecks": false,
15 "noEmit": true,
16 "baseUrl": ".",
17 "paths": {
18 "~/*": ["./*"],
19 "@/*": ["./*"]
20 },
21 "types": ["@types/jest", "@types/node", "@nuxt/vue-app"]
22 },
23 "exclude": [
24 "nuxt.config.ts",
25 "node_modules/**",
26 "dist/**",
27 ".nuxt/**",
28 "tests/**"
29 ]
30}

To add this file, I also need to add the following dependencies:

1{
2 "@nuxt/typescript": "2.7.1",
3 "@types/jest": "24.0.13",
4 "@types/node": "11.13.10",
5 "typescript": "3.4.5"
6}

Update eslintrc.js

1module.exports = {
2 plugins: ['@typescript-eslint'],
3 parserOptions: {
4 parser: '@typescript-eslint/parser',
5 },
6 extends: ['@nuxtjs', 'plugin:nuxt/recommended'],
7 rules: {
8 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
9 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
10 'no-unused-vars': 'off',
11 'vue/component-name-in-template-casing': [
12 'error',
13 'PascalCase',
14 {
15 ignores: ['nuxt', 'nuxt-link', 'nuxt-child', 'no-ssr'],
16 },
17 ],
18 'vue/html-closing-bracket-newline': [
19 'error',
20 {
21 singleline: 'never',
22 multiline: 'never',
23 },
24 ],
25 },
26};

And add some of the following dependencies:

1{
2 "@nuxtjs/eslint-config": "0.0.1",
3 "@typescript-eslint/eslint-plugin": "1.9.0"
4}

Rename nuxt.config.js to nuxt.config.ts

Change the file extension and make a few changes to the following:

1import NuxtConfiguration from '@nuxt/config';
2import { Configuration as WebpackConfiguration } from 'webpack';
3
4const config: NuxtConfiguration = {
5 mode: 'universal',
6 head: {},
7 build: {
8 extend(config: WebpackConfiguration, ctx) {},
9 },
10};
11
12export default config;

Refactor the Vuex Store

Because almost all the components in my project have used the Vuex Store, so I put this as the first for me to refactor before refactor the component. To use Vuex with TypeScript there are few changes compared to when using regular JavaScript, here are the changes that I am working on:

Classic Store

In this project I still use the Classic Store, which is actually deprecated and will be removed in Nuxt v3 in the future, the following classic store that I created in the store/index.ts file:

1import Vuex from 'vuex';
2
3import { state } from './state';
4import { mutations } from './mutations';
5import { actions } from './actions';
6
7const createStore = () => {
8 return new Vuex.Store({
9 state: state(),
10 mutations,
11 actions,
12 });
13};
14
15export default createStore;

State

In the state.ts file, I create an interface that is the type definitions of the state and creates a state with various initial value like the following example:

1export interface StateType {
2 isShowSidebar: boolean;
3}
4
5// initial state
6export const state = (): StateType => ({
7 isShowSidebar: false,
8});

Mutations

Vuex itself has provided support for TypeScript by providing data types in return for Mutations by simply importing MutationTree from Vuex, following the sample code:

1import { MutationTree } from 'vuex';
2import { StateType } from './state';
3import { Types } from './types';
4
5export const mutations: MutationTree<StateType> = {
6 [Types.SET_SHOW_SIDEBAR](state: StateType, data: boolean) {
7 state.isShowSidebar = data;
8 },
9};

Actions

For the actions themselves it is almost similar to the mutations in which the data type from Vuex has been provided, such as the following code example:

1import { ActionTree } from 'vuex';
2import { StateType } from './state';
3import { Types } from './types';
4
5export const actions: ActionTree<StateType, StateType> = {
6 setShowSidebar({ commit }, payload) {
7 commit(Types.SET_SHOW_SIDEBAR, payload);
8 },
9};

Refactor the Components

After successfully refactor the Vuex Store, then we will refactor our component code to support TypeScript.

To support TypeScript, we need to add some new dependencies like the following:

1{
2 "vue-class-component": "7.1.0",
3 "vue-property-decorator": "8.1.1",
4 "vuex-class": "0.3.2"
5}

First of all, of course we have to change the code in the single component file Vue that previously only <script></script> becomes <script lang = "ts"> </script>so we can support the TypeScript code in the script section . And here is the default.vue layout example that I refactor using TypeScript:

1import { Component, Vue } from 'vue-property-decorator';
2import { State, Mutation, Action } from 'vuex-class';
3
4import ArrowUpIcon from 'vue-ionicons/dist/js/ios-arrow-dropup-circle';
5import BaseHeader from '../components/BaseHeader.vue';
6import BaseSidebar from '../components/BaseSidebar.vue';
7import BaseToast from '../components/BaseToast.vue';
8
9@Component({
10 components: {
11 BaseHeader,
12 BaseSidebar,
13 BaseToast,
14 ArrowUpIcon,
15 },
16})
17export default class DefaultLayout extends Vue {
18 showArrowToTop = false;
19
20 @State settingActiveTheme;
21 @State isShowSidebar;
22
23 @Mutation setShowSidebar;
24
25 @Action initDataFromBrowserStorage;
26 @Action setWebshareSupport;
27
28 hideSidebar(): void {
29 this.setShowSidebar(false);
30 }
31
32 handleScroll(): void {
33 this.showArrowToTop = window.pageYOffset > 2000;
34 }
35
36 mounted() {
37 window.addEventListener('scroll', this.handleScroll);
38 }
39
40 beforedestroy() {
41 window.removeEventListener('scroll', this.handleScroll);
42 }
43}

As you can see from the code example above, I use vue-property-decorator ↗️ to define the component and use vuex-class ↗️ to bind the Vuex Store that was made beforehand so that it can be used in the component. Please visit the respective links to learn more about what we can and cannot do with vue-property-decorator or vuex-class.

Refactor the Jest Config

There is almost no need to change unit tests other than the path and file name that we are most likely to change the name and location. We only need to match the Jest configuration to support TypeScript as in the following code example:

1module.exports = {
2 moduleNameMapper: {
3 '^~/(.*)$': '<rootDir>/$1',
4 '^@/(.*)$': '<rootDir>/$1',
5 '^vue$': 'vue/dist/vue.common.js',
6 },
7 moduleFileExtensions: ['js', 'ts', 'vue', 'json'],
8 transform: {
9 '^.+.tsx?$': '<rootDir>/node_modules/ts-jest',
10 '^.+.js$': '<rootDir>/node_modules/babel-jest',
11 '^.+.vue$': '<rootDir>/node_modules/vue-jest',
12 },
13 globals: {
14 'ts-jest': {
15 diagnostics: false,
16 },
17 },
18};

Repository

🐙 https://github.com/mazipan/quran-offline ↗️

If you think this article is helpful
Loading comments...

Related Post...