I'm trying to run a dev server with TypeScript and an Angular application without transpiling ts files every time.
What I found is that I can run .ts files with ts-node but I want also to watch .ts files and reload my app/server. An example of this is the command gulp watch.
You can now simply npm install --save-dev ts-node nodemon and then run nodemon with a .ts file and it will Just Work:
nodemon app.ts
Previous versions:
I was struggling with the same thing for my development environment until I noticed that nodemon's API allows us to change its default behaviour in order to execute a custom command.
For example, for the most recent version of nodemon:
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"
Or create a nodemon.json file with the following content:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts" // or "npx ts-node src/index.ts"
}
and then run nodemon with no arguments.
By virtue of doing this, you'll be able to live-reload a ts-node process without having to worry about the underlying implementation.
And with even older versions of nodemon:
nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts
Or even better: externalize nodemon's config to a nodemon.json file with the following content, and then just run nodemon, as Sandokan suggested:
{
"watch": ["src/**/*.ts"],
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./index.ts"
}
I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev
https://github.com/whitecolor/ts-node-dev
Just run ts-node-dev src/index.ts
[EDIT]
Since I wrote this answer, nodemon has improved a lot, the required config is much lighter now and performance is much better. I currently use both (on different projects, obviously), and am satisfied with both.
Here's an alternative to the HeberLZ's answer, using npm scripts.
My package.json:
"scripts": {
"watch": "nodemon -e ts -w ./src -x npm run watch:serve",
"watch:serve": "ts-node --inspect src/index.ts"
},
-e flag sets the extenstions to look for,
-w sets the watched directory,
-x executes the script.
--inspect in the watch:serve script is actually a node.js flag, it just enables debugging protocol.
This works for me:
nodemon src/index.ts
Apparently thanks to since this pull request: https://github.com/remy/nodemon/pull/1552
Summary of options from other answers
nodemon plus ts-node is pretty stable but needs to be explicitly configured and is somewhat slow
node-dev plus ts-node requires much less configuration than nodemon but is still slow
ts-node-dev is fast but unreliable
Note that tsx (which uses ESBuild under the hood) and swc don't do type checking; this should be acceptable since most editors have type checking built-in, and type checking should still be part of your build process. You can also do type checking separately alongside your tests or as a pre-push hook via tsc --noEmit.
(Recommended) tsx
ⓘ TL;DR: fastest with minimal configuration
As of 2023-02-01, tsx seems to be the best combination of speed and minimal configuration:
Install tsx
npm install --save-dev tsx
Update your package.json, e.g.
"scripts: {
"dev": "tsx watch src/index.ts",
Run it
npm run dev
(Adjust these steps if you just want to install tsx globally and run it directly)
Alternative 1: nodemon/node-dev + ts-node + swc
ⓘ TL;DR: as fast as tsx but with more configuration
An alternative option that combines the reliability of nodemon/node-dev with the speed of ts-node-dev is to use ts-node with swc, a TypeScript-compatible transpiler implemented in Rust which is an "order of magnitude faster" than the TypeScript transpiler.
Install nodemon or node-dev (whichever you prefer)
nodemon
npm install --save-dev nodemon
node-dev
npm install --save-dev node-dev
Set up ts-node with swc integration
https://github.com/TypeStrong/ts-node#swc-1
Install necessary packages
npm install --save-dev ts-node #swc/core #swc/helpers regenerator-runtime
Add this to tsconfig.json
"ts-node": {
"swc": true
}
Run nodemon or node-dev, e.g
nodemon --watch src src/index.ts
or:
node-dev src/index.ts
Alternative 2: nodemon/node-dev + ts-node transpileOnly
ⓘ TL;DR: fast, reliable
Here's an alternative that's slower than the previous option because it uses the standard TypeScript transpiler, but in my testing it's still faster than nodemon/node-dev + ts-node.
Basically it's the same as the previous option but without swc. It's faster than out-of-the-box ts-node by disabling type checking (see notes above regarding why this should be acceptable).
Install nodemon/node-dev as above
Install ts-node
npm install --save-dev ts-node
Modify your tsconfig.json to enable transpileOnly for ts-node
"ts-node": {
"transpileOnly": true
}
Call nodemon/node-dev as above
Alternative 3: nodemon + tsc --incremental
ⓘ TL;DR: fast, reliable, type checking, more finicky
This is nearly the same speed as the previous alternative. The only real advantage of this over the other options is that it does type checking.
In terms of downsides, it can be a bit more finicky; in my testing, I'm using dotenv to pick up my .env file for local development. But depending how your tsc build is configured in tsconfig.json, you may have to do some acrobatics to get it working.
But it's good to have options, so here it is:
Install nodemon as above
(It's possible that this may work with node-dev as well, but I didn't see an exec option for node-dev)
Configure tsconfig.json to transpile your TypeScript to JavaScript
In particular, noEmit should not be set to true
Configure nodemon to run the TypeScript compiler to do an incremental transpilation any time a TypeScript file is changed, e.g.
"dev": "nodemon -e ts --watch src .env --exec \"tsc --incremental && node src/index.js\"",
You can even remove --incremental to further simplify it, but it will end up being much slower, comparable to nodemon/node-dev + ts-node.
you could use ts-node-dev
It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.
Install
yarn add ts-node-dev --dev
and your package.json could be like this
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
"prod": "tsc && node ./build/index.js"
}
Specifically for this issue I've created the tsc-watch library. you can find it on npm.
Obvious use case would be:
tsc-watch server.ts --outDir ./dist --onSuccess "node ./dist/server.js"
Add "watch": "nodemon --exec ts-node -- ./src/index.ts" to scripts section of your package.json.
i did with
"start": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts"
and yarn start.. ts-node not like 'ts-node'
I would prefer to not use ts-node and always run from dist folder.
To do that, just setup your package.json with default config:
....
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"prestart": "npm run build",
"start": "node .",
"dev": "nodemon"
},
....
and then add nodemon.json config file:
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "npm restart"
}
Here, i use "exec": "npm restart"
So all ts file will re-compile to js file and then restart the server.
To run while in dev environment,
npm run dev
Using this setup I will always run from the distributed files and no need for ts-node.
add this to your package.json file
scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}
and to make this work you also need to install ts-node as dev-dependency
yarn add ts-node -D
run yarn dev to start the dev server
Another way could be to compile the code first in watch mode with tsc -w and then use nodemon over javascript. This method is similar in speed to ts-node-dev and has the advantage of being more production-like.
"scripts": {
"watch": "tsc -w",
"dev": "nodemon dist/index.js"
},
The first step - Install the below packages in deDependencies
npm i -D #types/express #types/node nodemon ts-node tsc typescript
or using yarn
yarn add -D #types/express #types/node nodemon ts-node tsc typescript
The second step - using this configuration in your tsconfig.json file
{
"compilerOptions": {
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": [
"DOM",
"ES2017"
] /* Specify library files to be included in the compilation. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
"strict": true /* Enable all strict type-checking options. */,
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["node_modules"],
"include": ["./src"]
}
The third step - using these scripts in your package.json file
"scripts": {
"start": "node ./dist/server.js",
"dev": "nodemon -L ./src/server.ts && tsc -w"
},
STEP 1: You can simple install nodemon and ts-node (skip if you already done)
npm install --save-dev nodemon ts-node
STEP 2: You can configure the start script in package.json
"start": "nodemon ./src/app.ts"
As now nodemon automatically identify the typescript from the project now and use ts-node command by itself. Use npm start and it will automatically compile/watch and reload.
If you get any errors like typescript module not found in the project. simple use this command in the project folder.
npm link typescript
Just update these 3 packages
nodemon, ts-node, typescript
yarn global add nodemon ts-node typescript
or
npm install -g nodemon ts-node typescript
and now you can run this, problem solved
nodemon <filename>.ts
Clear logs of the console after changing
Javascript:
"start": "nodemon -x \"cls && node\" index.js",
Typescript:
"start": "nodemon -x \"cls && ts-node\" index.ts",
If you are having issues when using "type": "module" in package.json (described in https://github.com/TypeStrong/ts-node/issues/1007) use the following config:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm --experimental-specifier-resolution ./src/index.ts"
}
or in the command line
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "node --loader ts-node/esm --experimental-specifier-resolution src/index.ts"
With nodemon and ts-node:
nodemon --watch source --ext ts,json --exec "node --loader ts-node/esm ./source/index.ts"
I started working a lot with vue and started to use it in all the projects in the company where I work. And with that, I ended up creating some components, in general autocomplete, I know that there are many, I have already used some, but none have supplied all my needs. However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it.
So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ..., and also be able to contribute a bit with the community.
update
With the release of vue-loader 15.x this answer will no longer work. Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f
Here is one way you can create/publish a Vuejs library/component from scratch.
As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM.
After you publish it, like most libraries you can install it using ex:
npm install --save your-component
And then import the component inside your app using
import something from 'your-component'
To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run:
npm init
Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code.
(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.)
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
After this, we'll need to install the dependencies for our library.
These dependencies are divided into two types: dependency and devDependency
dependency:
is the external library or libraries that our own component runs on. When someone installs your component, npm will make sure this dependency exists or gets installed first. Since we are creating a component for vue, we need to make sure vue is required. So, install it using:
npm install --save vue
devDependency:
is a bunch of libraries that we need only for development purposes. These libraries will help us build and/or transpile.
We install dev dependencies using the method above by adding the the suffix -dev to --save
Now, let us install the minimum dev dependencies we need for our component:
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
At this point the libraries will be installed and the package.json will be updated to look like following.
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"vue": "^2.5.9"
}
}
(note: I have added "build": "webpack -p" to build our lib with webpack)
Now, since our code needs to be built and transpiled, we need a folder to store the build version. Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js
All of the files we have so far created are for configuring and stuff. For the actual app that people are going to use, we need to create at least two files inside our src/ directory.
A main.js and VuejsHelloApp.vue put them as:
./src/main.js and ./src/components/VuejsHelloApp.vue
I have mine structured like this:
dist
node_modules
src
main.js
components
VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js
I will just go through the files listed and describe what each file does in-case anyone is curious:
/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores
node_modules I think we know this already, let's ignore it
src/ this is root dir of your library.
.babelrc is where your babel options are kept, so add this to disable presets on modules
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
.eslintignore This is where you tell ESLINT to ignore linting so put this inside:
build/*.js
.gitignore
add files you want to ignore (from git)
.npmignore same as .gitignore for NPM
.travis.yml if you need CI check examples from travis and configure it
CONTRIBUTING not required
LICENSE not required
package.json ignore for now
README.md not required
webpack.config.js This is the important file that let's you create a build, browser compatible version of your code.
So, according to our app, here is a minimal example of what it should look like:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
module: {
rules: [
// use babel-loader for js files
{ test: /\.js$/, use: 'babel-loader' },
// use vue-loader for .vue files
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// default for pretty much every project
context: __dirname,
// specify your entry/main file
output: {
// specify your output directory...
path: path.resolve(__dirname, './dist'),
// and filename
filename: 'vuejs-hello-app.js'
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Note that the important directives here are entry and output. You can check webpack docs to learn more if you want to fully customize your app.
But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js
Now, we are almost finished setting up everything except the actual app.
Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it
<template>
<div>
<button #mouseover='move($event)'> I'm alive </button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
move (event) {
let pos = event.target.style.float;
if(pos === 'left'){
event.target.style.float = 'right'
}else{
event.target.style.float = 'left'
}
}
}
}
</script>
<style scoped>
</style>
And not but not least, got to ./src/main.js and export your app like:
import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp
Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js",
After this, simply run these commands to build and publish your app:
npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login
npm publish
Importing and using the library.
If everything went smoothly, then simply install your app like this:
npm install --save vuejs-hello-app
And use it in vue like this:
<template>
<div>
<VuejsHelloApp> </VuejsHelloApp>
</div>
</template>
<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
name: 'HelloWorld',
components: { VuejsHelloApp }
}
</script>
I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code
Trying to do what I thought was a simple thing.
I have a node package that uses advanced js syntax. I want to depend on it in a react project.
So I installed babel packages via --save-dev, and added a .babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread"]
}
That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:
{
"name": "bla",
"version": "1.0.0",
"scripts": {
"postinstall": "babel src --out-dir lib"
},
"main": "lib/index.js",
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react-native": "^4.0.0"
}
}
When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.
Why is this so difficult? What am I doing wrong?
sh: 1: babel: not found is from your shell not finding the babel binary file (normally under ./node_modules/.bin/babel)
You'd want to compile before you publish to npm, so anyone who installs your package has the built files. But, for Github try something like:
"postinstall": "npx babel src --out-dir lib"
This hack worked instead of the postinstall:
...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...
Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098
Also relevant: https://github.com/npm/npm/issues/10366
I am not sure I understand the need here correctly, but could you not just run the babel call in prepare or prepublish scripts? That way only local npm install calls would pick that up.
See more about npm scripts lifecycle: https://docs.npmjs.com/misc/scripts
Is there a way to use the babel client without installing it globally?
So rather than this
npm install -g babel-cli
I'd like to do this
npm install babel-cli --save-dev
Any local package's binary can be accessed inside npm scripts as if it was installed globally:
// package.json
{
"scripts": {
"build": "babel ..."
}
}
If you want to execute the binary on the command line, you can use a relative path to node_modules/.bin/:
$ node_modules/.bin/babel ...
This is related to first example: node_modules/.bin/ is simple added to the PATH of the environment the npm scripts are executed in.
you can put something like this:
{
"scripts": {
"start": "babel-node test.js"
}
}
in your package.json where test.js is a script which you want to run. Now you can run it with npm start command
Yes, you could install locally and run from node_modules:
./node_modules/.bin/babel
If you have a local package.json you could add an NPM script to simplify the command, since NPM scripts run with ./node_modules/.bin on the PATH:
"scripts": {
"babel": "babel ...",
}
To run from any directory under package.json:
$ npm run babel
If you just want to run test with command "npm test testFile.js". This is my package.json:
"scripts": {
"build": "babel-node",
"test": "node_modules/.bin/babel-node"
}