How to compile typescript using npm command?

前端 未结 3 986
北海茫月
北海茫月 2021-01-31 10:13

Well I just wanted to know is there any command which will directly compile the typescript code and get the output. Right now, what i am doing is,every time when i make changes

3条回答
  •  耶瑟儿~
    2021-01-31 10:39

    Here is my approach, let say that you keep all your typescript files in src folder and want outputted javascript files be generated in the ./dist folder.

    {
        "name": "yourProjectName",
        "version": "1.0.0",
        "description": "",
        "main": "./dist/index",
        "types": "./dist/index",
        "scripts": {
            "dev": "tsc --watch & nodemon dist"
        },
        "author": "Gh111",
        "license": "ISC",
        "devDependencies": {
            "yourdevDependencies": "^1.0.0"
        }
    }
    

    and typescript configuration file tsconfig.json

    {
      "compilerOptions": {
        "target": "es5",       
        "module": "commonjs",  
        "outDir": "./dist",    
      },
      "include": ["./src/**/*"],
      "exclude": [
        "node_modules"
      ]
    }
    

    Okay, what is going on here

    First of all we should create tsconfig.json and tell typescript to put compiled files into the ./dist folder and at the same time we should exclude node_module folder or whatever we want and include everything from ["./src/**/*"] directory.

    After that in packages.json file we should specify path to our compiled index.js file

    "main": "./dist/index"

    and finally we tell tsc to --watch any typescript changes, and nodemon to watch inside ./dist directory and if something changes nodemon will restart the server.

    "scripts": {
        "dev": "tsc --watch & nodemon dist"
     },
    

    To run script type npm run dev

提交回复
热议问题