nodemon not watching workspace dependencies - javascript

I use nodemon to watch file changes in a TypeScript Node.JS codebase. When a change is detected, esbuild and esbuild-register are used to transpile the code to CommonJS files and the application restarts.
The application is part of a monorepo with yarn workspaces. I use some code from a shared package in my application.
How can i get nodemon to automatically watch dependencies from the same workspace for changes and trigger a restart?
My workaround is adding the relative path to all used linked dependencies in watch in nodemon.json, but that requires me to manually edit the configuration when I add a local linked dependency.
nodemon.json
{
"exec": "node -r esbuild-register",
"ext": "ts,json",
"watch": [
"src",
"../../packages/logger/src",
"../../packages/helpers/src"
],
"ignore": [
"node_modules"
]
}
package.json
{
"dependencies": {
"#app/logger": "*",
"#app/helpers": "*"
}
}

Related

Enable global ESlint config

I want to make a eslint config works globally, so that I don't need to init it in each project.
then I installed eslint and some config extension globally.
npm install -g eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
And this is my eslint config file ~/.eslintrc.json
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"airbnb-base"
],
"rules": {
}
}
But I got error when I lint my js file
ESLint couldn't find the config "airbnb-base" to extend from. Please check that the name of the config is correct.
The config "airbnb-base" was referenced from the config file in "/home/molly/.eslintrc.json".
This is my global installed packages, airbnb is there.
Did I miss something ? I don't want to install eslint-plugin** in each of project
Probably a bit late for you but I don't think you can install eslint plugins globally.
The way around that worked for me is to create a directory where all my projects go and inside that directory create a package.json (npm init -y) and install all the plugins in that directory npm i -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
Bring your global .eslintrc file in that directory which will act like a root eslint config for all your projects that's inside that directory now.
Essentially, your directory tree should like the following now:
projects/
package.json
.eslintrc
node_modules/
...
my_cool_project/
...
my_cool_project2/
...
...

How do I make Vite build my files every time a change is made?

I'm trying to make Vite build my files and output them into the dist folder every time I save/make changes on to my files during development.
How would I do that?
Here is my vite.config.development.js file:
import { defineConfig } from "vite";
export default defineConfig({
base: "./",
build: {
rollupOptions: {
output: {
assetFileNames: "assets/[name].[ext]",
chunkFileNames: "assets/[name].[ext]",
entryFileNames: "assets/[name].js",
},
},
write: true,
},
});
Here is my scripts in package.json:
"frontend-dev": "vite --config vite.config.development.js",
It does the usual localhost:3000 thing, but it does not build my files and put them in the dist folder when I make changes to my source code.
Currently, I have to run a vite build npm script every time which takes a lot of time.
If you want Vite to do a rebuild on file changes, you can use the --watch flag:
vite build --watch
In your case, with a custom config file:
vite build --watch --config vite.config.development.js
With the --watch flag enabled, changes to the config file, as well as any files to be bundled, will trigger a rebuild and will update the files in dist.
Do you know NodeJS? If you know NodeJS, you can monitor folders and files with the fs module. By monitoring the src directory, you can trigger the vite whenever there is a change. This is the manual solution. I don't know if there are currently npm packages that provide this.
NodeJS Filestream Watch
Building on #Mussini's answer, you got options:
add --watch and optional --config vite build --watch --config vite.config.ts on cli
or add to package.json:
{
"name": "frontend",
...
"scripts": {
"dev": "vite",
...
"build-watch": "vite build --watch --config ./vite.config.ts",
"build": "vite build",
or integrate --watch into the vite.config.ts which adds watching to the build cmd by default (vite build does not exit!)
export default defineConfig({
build: {
watch: './vite.config.ts',
You likely want option 2 and use with npm run build-watch

How do I setup nodemon to make it watch for changes in typescript source file? [duplicate]

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"

How to create and publish a Vuejs component on NPM

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

nodemon watch directory for changes

I know how to do nodemon server.js but what if I want to do nodemon ./src
I want restart node on any changes in the directory of src.
When I do above and it say cannot find module babelprac\src
I am also doing in another command window : npm run scripts:watch
The script is
"scripts" : {
"scripts" : "babel src --source-maps-inline --out-dir dist",
"scripts:watch" : "babel src --watch --source-map-inline --out-dir dist"
},
That runs the watch but I want to run the script in src or dist to see the console.logs
I aslo tried nodemon --watch ./src. It says it can't find index.js.
I am on windows 7
My working directory is babelprac
Nodemon expects it just as:
nodemon --watch src server.js
https://github.com/remy/nodemon#monitoring-multiple-directories
nodemon --watch app --watch libs app/server.js
Nodemon also has a more fine-grained approach for watching folders and files. Use nodemon.json to specify what files and the types of files to watch, as below in your case:
{
"watch": ["server.js", "src/"],
"ext": "js, css"
}
Having a nodemon.json is particularly useful when the number and types of watched files start to bloat, and also when you want to run a script upon each server restart. For nodemon to read in the configuration, nodemon.json should be placed at the root directory of your project, along with every other hidden and not hidden json files.
Below is a good place to start your nodemon.json.
https://github.com/remy/nodemon/blob/master/doc/sample-nodemon.md
I use this for hot replacement, nodemon --watch src and run tsc complier.
you can also check this article:
https://medium.com/netscape/start-building-web-apps-with-koajs-and-typescript-366264dec608
"scripts": {
"watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node' ./src/server.ts"
}
This solution worked for me. In the first create a file name nodemon.json in the home directory of your project and then add this
{
"restartable": "rs",
"ignore": [
".git",
"node_modules/**/node_modules"
],
"verbose": true,
"execMap": {
"js": "node --harmony"
},
"events": {
"restart": "osascript -e 'display notification \"App restarted due to:\n'$FILENAME'\" with title \"nodemon\"'"
},
"watch": [
"test/fixtures/",
"test/samples/"
],
"env": {
"NODE_ENV": "development"
},
"ext": "js,json"
}
you can add your directory name in the "watch" option to be monitored by the nodemon for any changes and add your files type in the "ext" option
Install it:
npm install npm-watch
"scripts":
"watch": "npm-watch"

Categories