How can I switch to a different ESLint style guide? - javascript

I started a new Vue project with vue-cli and Webpack and configured ESLint to Airbnb's style guide.
How can I change this choice to a Standard style? I am getting really tired of the surplus in commas and semicolons, and want to give it Standard JS a try.
I am working alone at this project right now, so do not worry about team complains :)

Just install StandardJS via npm install standard --save-dev.
Then run through the rules just to quickly get a feel of it.
Finally, create a script in your package.json to run StandardJS, when you need it:
{
"scripts": {
"check": "standard"
}
}
...then you can run it via npm run check
To provide a quick way to yourself to fix most coding style typos, add a fix script to your package.json:
{
"scripts": {
"check": "standard",
"fix": "standard --fix"
}
}
...and run via npm run fix
To get a more nicer representation of coding style errors, install snazzy via npm install snazzy --save-dev, then modify your package.json like so:
{
"scripts": {
"check": "standard --verbose | snazzy",
"fix": "standard --fix"
}
}

Related

import React, { useState } from 'react'; ^^^^^^ SyntaxError: Cannot use import statement outside a module [duplicate]

I've got an ApolloServer project that's giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My "index.js" is:
require('dotenv').config()
import {startServer} from './server'
startServer()
And when I run it I get the error
SyntaxError: Cannot use import statement outside a module
First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the "import" to a "require" and this worked.
But now I have about two dozen "imports" in other files giving me the same error.
*I'm sure the root of my problem is that I'm not even sure what's complaining about the issue. I sort of assumed it was Babel 7 (since I'm coming from Babel 6 and I had to change the presets) but I'm not 100% sure.
Most of what I've found for solutions don't seem to apply to straight Node. Like this one here:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
Says it was resolved by adding "type=module" but this would typically go in the HTML, of which I have none. I've also tried using my project's old presets:
"presets": ["es2015", "stage-2"],
"plugins": []
But that gets me another error: "Error: Plugin/Preset files are not allowed to export objects, only functions."
Here are the dependencies I started with:
"dependencies": {
"#babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",
Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If anyone is running into this issue with TypeScript, the key to solving it for me was changing
"target": "esnext",
"module": "esnext",
to
"target": "esnext",
"module": "commonjs",
In my tsconfig.json. I was under the impression "esnext" was the "best", but that was just a mistake.
For those who were as confused as I was when reading the answers, in your package.json file, add
"type": "module"
in the upper level as show below:
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
According to the official documentation:
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node.js treat your file as an ES module, you need to (Enabling):
add "type": "module" to package.json
add "--experimental-modules" flag to the Node.js call
I ran into the same issue and it's even worse: I needed both "import" and "require"
Some newer ES6 modules works only with import.
Some CommonJS works with require.
Here is what worked for me:
Turn your js file into .mjs as suggested in other answers
"require" is not defined with the ES6 module, so you can define it this way:
import { createRequire } from 'module'
const require = createRequire(import.meta.url);
Now 'require' can be used in the usual way.
Use import for ES6 modules and require for CommonJS.
Some useful links: Node.js's own documentation. difference between import and require. Mozilla has some nice documentation about import
I had the same issue and the following has fixed it (using Node.js 12.13.1):
Change .js files extension to .mjs
Add --experimental-modules flag upon running your app.
Optional: add "type": "module" in your package.json
More information: https://nodejs.org/api/esm.html
First we'll install #babel/cli, #babel/core and #babel/preset-env:
npm install --save-dev #babel/cli #babel/core #babel/preset-env
Then we'll create a .babelrc file for configuring Babel:
touch .babelrc
This will host any options we might want to configure Babel with:
{
"presets": ["#babel/preset-env"]
}
With recent changes to Babel, you will need to transpile your ES6 before Node.js can run it.
So, we'll add our first script, build, in file package.json.
"scripts": {
"build": "babel index.js -d dist"
}
Then we'll add our start script in file package.json.
"scripts": {
"build": "babel index.js -d dist", // replace index.js with your filename
"start": "npm run build && node dist/index.js"
}
Now let's start our server.
npm start
I Tried with all the methods, but nothing worked.
I got one reference from GitHub.
To use TypeScript imports with Node.js, I installed the below packages.
1. npm i typescript --save-dev
2. npm i ts-node --save-dev
Won't require type: module in package.json
For example,
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
Step 1
yarn add esm
or
npm i esm --save
Step 2
package.json
"scripts": {
"start": "node -r esm src/index.js",
}
Step 3
nodemon --exec npm start
Node v14.16.0
For those who've tried .mjs and got:
Aviator#AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.mjs
file:///mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.mjs:3
import fetch from "node-fetch";
^^^^^
SyntaxError: Unexpected identifier
and who've tried import fetch from "node-fetch";
and who've tried const fetch = require('node-fetch');
Aviator#AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.js
(node:4899) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.js:3
import fetch from "node-fetch";
^^^^^^
SyntaxError: Cannot use import statement outside a module
and who've tried "type": "module" to package.json, yet continue seeing the error,
{
"name": "test",
"version": "1.0.0",
"description": "to get fetch working",
"main": "just_js.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT"
}
I was able to switch to axios without a problem.
import axios from 'axios'; <-- put at top of file.
Example:
axios.get('https://www.w3schools.com/xml/note.xml').then(resp => {
console.log(resp.data);
});
I found the 2020 update to the answer in this link helpful to answering this question as well as telling you WHY it does this:
Using Node.js require vs. ES6 import/export
Here's an excerpt:
"Update 2020
Since Node v12, support for ES modules is enabled by default, but it's still experimental at the time of writing this. Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules."
I'm new to Node.js, and I got the same issue for the AWS Lambda function (using Node.js) while fixing it.
I found some of the differences between CommonJS and ES6 JavaScript:
ES6:
Add "type":"module" in the package.json file
Use "import" to use from lib.
Example: import jwt_decode from jwt-decode
Lambda handler method code should be define like this
"exports.handler = async (event) => { }"
CommonJS:
Don't add "type":"module" in the package.json file
Use "require" to use from lib.
Example: const jwt_decode = require("jwt-decode");
The lambda handler method code should be defines like this:
"export const handler = async (event) => { }"
In my case. I think the problem is in the standard node executable. node target.ts
I replaced it with nodemon and surprisingly it worked!
The way using the standard executable (runner):
node target.ts
The way using the nodemon executable (runner):
nodemon target.ts
Do not forget to install nodemon with npm install nodemon ;P
Note: this works amazing for development. But, for runtime, you may execute node with the compiled js file!
To use import, do one of the following.
Rename the .js file to .mjs
In package.json file, add {type:module}
If you are using ES6 JavaScript imports:
install cross-env
in package.json change "test": "jest" to "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
more in package.json, add these:
...,
"jest": {
"transform": {}
},
"type": "module"
Explanation:
cross-env allows to change environment variables without changing the npm command. Next, in file package.json you change your npm command to enable experimental ES6 support for Jest, and configure Jest to do it.
This error also comes when you run the command
node filename.ts
and not
node filename.js
Simply put, with the node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node.
If you want to use BABEL, I have a simple solution for that!
Remember this is for nodejs example: like an expressJS server!
If you are going to use react or another framework, look in the babel documentation!
First, install (do not install unnecessary things that will only trash your project!)
npm install --save-dev #babel/core #babel/node
Just 2 WAO
then config your babel file in your repo!
file name:
babel.config.json
{
"presets": ["#babel/preset-env"]
}
if you don't want to use the babel file, use:
Run in your console, and script.js is your entry point!
npx babel-node --presets #babel/preset-env -- script.js
the full information is here; https://babeljs.io/docs/en/babel-node
I had this error in my NX workspace after upgrading manually. The following change in each jest.config.js fixed it:
transform: {
'^.+\\.(ts|js|html)$': 'jest-preset-angular',
},
to
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
},
I had this issue when I was running migration
Its es5 vs es6 issue
Here is how I solved it
I run
npm install #babel/register
and add
require("#babel/register")
at the top of my .sequelizerc file my
and go ahead to run my sequelize migrate.
This is applicable to other things apart from sequelize
babel does the transpiling
Just add --presets '#babel/preset-env'.
For example,
babel-node --trace-deprecation --presets '#babel/preset-env' ./yourscript.js
Or
in babel.config.js
module.exports = {
presets: ['#babel/preset-env'],
};
To make your import work and avoid other issues, like modules not working in Node.js, just note that:
With ES6 modules you can not yet import directories. Your import should look like this:
import fs from './../node_modules/file-system/file-system.js'
For people coming to this thread due to this error in Netlify functions even after adding "type": "module" in package.json file, update your netlify.toml to use 'esbuild'. Since esbuild supports ES6, it would work.
[functions]
node_bundler = "esbuild"
Reference:
https://docs.netlify.com/functions/build-with-javascript/#automated-dependency-bundling
The documentation is confusing. I use Node.js to perform some local task in my computer.
Let's suppose my old script was test.js. Within it, if I want to use
import something from "./mylocalECMAmodule";
it will throw an error like this:
(node:16012) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module
...
This is not a module error, but a Node.js error. Forbid loading anything outside a 'module'.
To fix this, just rename your old script test.js into test.mjs.
That's all.
My solution was to include babel-node path while running nodemon as follows:
nodemon node_modules/.bin/babel-node index.js
You can add in your package.json script as:
debug: nodemon node_modules/.bin/babel-node index.js
NOTE: My entry file is index.js. Replace it with your entry file (many have app.js/server.js).
I had the same problem when I started to use Babel... But later, I
had a solution... I haven't had the problem any more so far...
Currently, Node.js v12.14.1, "#babel/node": "^7.8.4", I use babel-node and nodemon to execute (Node.js is fine as well..)
package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js"!! Note: server.js is my entry
file, and you can use yours.
launch.json. When you debug, you also need to configure your launch.json file "runtimeExecutable":
"${workspaceRoot}/node_modules/.bin/babel-node"!! Note: plus
runtimeExecutable into the configuration.
Of course, with babel-node, you also normally need and edit another file, such as the babel.config.js/.babelrc file
In case you're running nodemon for the Node.js version 12, use this command.
server.js is the "main" inside package.json file, replace it with the relevant file inside your package.json file:
nodemon --experimental-modules server.js
I recently had the issue. The fix which worked for me was to add this to file babel.config.json in the plugins section:
["#babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true,
"loose": true,
"lazy": true
}],
I had some imported module with // and the error "cannot use import outside a module".
If you are using node, you should refer to this document. Just setup babel in your node app it will work and It worked for me.
npm install --save-dev #babel/cli #babel/core #babel/preset-env
When I used sequelize migrations with npx sequelize db:migrate, I got this error, so my solution for this was adding the line require('#babel/register'); into the .sequelizerc file as the following image shows:
Be aware you must install Babel and Babel register.
Wrong MIME-Type for JavaScript Module Files
The common source of the problem is the MIME-type for "Module" type JavaScript files is not recognized as a "module" type by the server, the client, or the ECMAScript engine that process or deliver these files.
The problem is the developers of Module JavaScript files incorrectly associated Modules with a new ".mjs" (.js) extension, but then assigned it a MIME-type server type of "text/javascript". This means both .js and .mjs types are the same. In fact the new type for .js JavaScript files has also changed to "application/javascript", further confusing the issue. So Module JavaScript files are not being recognized by any of these systems, regardless of Node.js or Babel file processing systems in development.
The main problem is this new "module" subtype of JavaScript is yet known to most servers or clients (modern HTML5 browsers). In other words, they have no way to know what a Module file type truly is apart from a JavaScript type!
So, you get the response you posted, where the JavaScript engine is saying it needs to know if the file is a Module type of JavaScript file.
The only solution, for server or client, is to change your server or browser to deliver a new Mime-type that trigger ES6 support of Module files, which have an .mjs extension. Right now, the only way to do that is to either create a HTTP content-type on the server of "module" for any file with a .mjs extension and change your file extension on module JavaScript files to ".mjs", or have an HTML script tag with type="module" added to any external <script> element you use that downloads your external .js JavaScript module file.
Once you fool the browser or JavaScript engines into accepting the new Module file type, they will start doing their scripting circus tricks in the JS engines or Node.js systems you use.

How do I configure parcel to exit build with an error if eslint does not validate

I'm building a react app with parcel. I have an eslint config set up that I like, and use VSCode tools to catch eslint errors and fix them as I code. The app builds correctly as of now. So all that is fine.
However, as an added precaution, I would like to set up parcel to run eslint, using my config, and to halt the build process and output an error when I havent followed the eslint rules, either when running dev server or building for production.
I'm aware of this npm package from googling, but the package doesnt have a readme, and i can't find setup instructions in the parcel docs: https://www.npmjs.com/package/#parcel/validator-eslint
For reference I am using parcel 1.12.3 but would be open to changing to parcel 2.x.x if that is neccesary.
Thanks!
In parcel v2, you can use the #parcel/validator-eslint plugin to accomplish this. Here's how:
Install eslint and #parcel/validator-eslint in your project. Note that this plugin will currently only work with eslint v7 or earlier due to this bug (which hopefully we can fix soon ;-))
yarn add -D eslint#7 #parcel/validator-eslint
Add an .eslintrc.json file to your project with your configuration. It's best to use a static config file (like .json or .yaml) rather than a dynamic one (like .js) if you can, because that helps parcel's caching be more efficient and faster (see docs). Here's a basic file example that works, but you can extend this to suit your needs by checking out the eslint docs:
{
"env": {
"browser": true
},
"extends": [
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
}
}
Tell configure parcel to use the plugin for javascript files by adding a .parcelrc file at the root of your project (or modify your existing .parcelrc file to include the "validators" entry below):
{
"extends": "#parcel/config-default",
"validators": {
"*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx}": [
"#parcel/validator-eslint"
]
}
}
Now, if you have an eslint error, it should bubble up through parcel like this:
🚨 Build failed.
#parcel/validator-eslint: ESLint found 1 errors and 0 warnings.
C:\Users\ansteg\Projects\parcel-eslint-example\src\index.js:2:7
1 | // This unused variable should trigger an ESLint error.
> 2 | const unusedVar = "Hello!";
> | ^^^^^^^^^^ 'unusedVar' is assigned a value but never used.
3 |
See this github repo for a working example.

mocha.opts deprecated, how to migrate to package.json?

I'm working on a massive project and since last week I updated mocha, Now we are getting warning:
DeprecationWarning: Configuration via mocha.opts is DEPRECATED and
will be removed from a future version of Mocha. Use RC files or
package.json instead.
I want to migrate the options to package.json but there is no good migration guide. all posts on GitHub with similar questions are all answered "see the docs". But the docs doesn't show how to transfer one option from mocha.opts to package.json, there is no information on how it should be formatted. Only thing I can find is that the "spec" property is the pattern for files to run. Nothing else seems implicit to me.
Our mocha.opts file:
--reporter dot
--require test/mocha.main
--recursive src/**/*.test.js
--grep #slow --invert
My attempt which doesn't work:
"mocha": {
"reporter": "dot",
"require": "test/mocha.main",
"spec": "src/**/*.test.js",
"grep": "#slow --invert"
},
Please explain how I should format this configuration block in order to achieve samme behaviour as when using the options from the above mocha.opts
I too had some difficulties finding the exact solution for migrating to new standards and could finally resolve those. I hope I'm not too late and I can still help you.
So first thing, you would need a new config file to replace mocha.opts. Mocha now offers quite some variations of file formats which can be used for it. You can find these here in their GIT. I took .mocharc.json and will be using it for further examples. Although adding it didn't change anything just the way it shows no effect for you too.
The catch was to point mocha test script to this config file in package.json. Provide --config flag in the test script in the scripts section in your package.json like below.
"scripts": {
"test": "mocha --config=test/.mocharc.json --node-env=test --exit",
"start": "node server"
}
Now you can update your configs in the .mocharc.json file and they should reflect correctly. Below is an example of it.
{
"diff": true,
"extension": ["js"],
"package": "../package.json",
"reporter": "spec",
"slow": 1500,
"timeout": 20000,
"recursive": true,
"file": ["test/utils/helpers.js", "test/utils/authorizer.js"],
"ui": "bdd",
"watch-files": ["lib/**/*.js", "test/**/*.js"],
"watch-ignore": ["lib/vendor"]
}
I'm using file property to define which files should go first as they need to be executed first. They will be executed in the order you provide them in the file array. Another property you can play around is slow whose value defines whether mocha consider the time taken to execute any test case as slow or not.
Check out this link to see the new format of the options file for mocha:
https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.yml
Basically you need a .mocharc.yml, or .mocharc.json, (there are a couple more formats) to set the mocha configurations. I came to this POST hoping to find an answer too. Hope this is helpful for you!
I ended up getting the package.json working by using an array instead of the string literals you did.
ex:
"mocha": {
"require": ["tsconfig/register"]
}
Might be worth a try!
Seems like mocha won't check the package.json for config by default so you need to pass --package package.json.
/* This example illustrates how to configure mocha globally
*1. add the 'mocharch.json' to link mocha to the 'package.json' like so:
*/
{
"package": "./package.json"
}
/* 2. in the 'package.json' add: */
"mocha": {
"recursive": "true"
}
The answer by Rathore is great, but I just wanted to point out that if you just add the .mocharc.json file to your base directory, you don't need to specify "--config=test/.mocharc.json" in your package.json, it just finds it automatically.
you can create .mocharc.json in project root folder.
{
"spec": "src/tests/**/*.ts",
"require": "ts-node/register"
}
in package.json add mocha property.
"mocha": {
"spec": ["src/tests/**/*.ts"],
"require": ["ts-node/register"]
}
js project change file name.

How to make Visual Studio Code check entire project for errors?

I'm using VS Code for TypeScript/JavaScript development. When I open a file it will check that file for errors. The problem is if I'm refactoring (like I move some shared code to a new location or change a name) it won't show me the errors this caused until I open the file with the problem. ...so if I want to do extensive refactoring I have to open every file just to make it scan the file for errors.
How can I make VS Code scan the whole project for errors without having to open each file one by one manually?
VS Code (v1.44) has an experimental feature, that allows project wide error reporting in TS. Try it out:
// put this line in settings.json
"typescript.tsserver.experimental.enableProjectDiagnostics": true
Figured it out. Note this answer is specific to TypeScript, which is what I am using. Here it is:
Make sure typescript is installed globally (I just had mine installed locally apparently):
npm install -g typescript
Then in VS Code press Shift+Ctrl+B. If you don't have a task runner set up it will ask what you want. I selected typescript and the tasks.json file will look like this:
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p", "."],
"showOutput": "silent",
"problemMatcher": "$tsc"
}
Then pressing Shift+Ctrl+B (or Shift+Command+B in macOS) will check the entire project for problems and they will be reported in your "problems" panel.
If you don't want to install TypeScript globally, you can do the following:
Install TypeScript locally on the project, that is yarn add --dev typescript or npm install --save-dev typescript.
Add a check-types run script to ./package.json. --noEmit means that the compiler will won't generate any JavaScript files.
{
"scripts": {
"check-types": "tsc --noEmit"
}
}
Let VSCode know about the run script in /.vscode/tasks.json.
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "check-types",
"problemMatcher": [
"$tsc"
]
}
]
}
To run the tasks hit the F1 key and select 'Run Task', and then 'npm: check-types'.
If you add the following lines to the task, pressing Ctrl+B will run it.
"group": {
"kind": "build",
"isDefault": true
}
For the most recent version of tasks.json this is the correct json, following deprecations in version 1.14. Create this as /.vscode/tasks.json
{
"version": "2.0.0",
"command": "tsc",
"type": "shell",
"args": [
"-p",
"."
],
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$tsc"
}
Once you have open your project in vs code, open the vs code terminal and run:
node_modules/.bin/tsc --noEmit
Go to View menu > Extensions and make sure the Microsoft VS Code ESLint extension is installed.
In Settings, search for "ESLint > Lint Task: Enable", and enable that setting (docs).
In the Terminal menu, choose Run Task… > eslint: lint whole folder.
UPDATE.
My answer below does not answer the original question, but if you're like me and have found this thread searching for how to turn on // #ts-check project-wide in VSCode so that you don't need to add // #ts-check to every file then my answer below is what you need. I have searched and searched and kept getting this thread as my top result so hopefully this helps others as well
I'm on vscode version 1.52.1 and the answer is so simple and right on the vscode website:
https://code.visualstudio.com/docs/nodejs/working-with-javascript#_type-checking-javascript
scroll down to the "Using jsconfig or tsconfig" section
Add a jsconfig.json in your project root and add "checkJs": true
{
"compilerOptions": {
"checkJs": true
},
"exclude": ["node_modules", "**/node_modules/*"]
}
You might need to restart vscode once you add it in
None of the other solutions worked fully for me. Here's a tasks.json that does, working with vscode 1.67+. On Linux etc. set command to tsc, on Windows be sure to run tsc.cmd as tsc alone will attempt to run the bash script and produce the following error:
The terminal process failed to launch: A native exception occurred during launch (Cannot create process, error code: 193)
"revealProblems": "always" in the presentation section shows the Problems panel on completion.
{
"version": "2.0.0",
"tasks": [
{
"label": "tsc: error check project",
"command": "tsc.cmd",
"args": [
"-p",
".",
"--noEmit"
],
"isBackground": false,
"problemMatcher": "$tsc",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"revealProblems": "always",
}
}
]
}
Edit: Since updating to 1.52.0 this no longer works. It will instead replace the current project files with what you selected...
===
I've tried every solution I can find and I think it's safe to say the answer is: You can't*
The best I've found is still technically opening each file manually, but at least it's not one-by-one:
You can't drag/drop a directory but you can select multiple files (including directories) and drag/drop. The directories will be ignored and any files you had selected will be opened in tabs.
Next, you need to give each tab focus so it triggers eslint to run. (Holding down the next tab keyboard shortcut works.)
This is terrible and I beg someone to prove me wrong.
*I haven't found a way that works as well as opening files manually. Each method -- experimental vscode feature and tsc task -- has its own set of drawbacks. The vscode feature is clearly the solution but without a way to ignore node_modules, etc. it's too painful to use.

Foreverjs tries to find module in /node_modules/my-module/node_modules/my-module

I use foreverjs to start my services. Also I use nodejs v5 with nvm. Running on mac.
Everything working fine yesterday, but today (after npm update) I suddenly have an errors like /node_modules/my-service-one/node_modules/my-service-onewhen I'm try to npm start.
The project structure is:
.
|-package.json
|-services.json
|+-node_modules
|-forever
|-my-service-one
|-my-service-two
Config for foreverjs (services.json):
[
{
"append": true,
"uid": "my-service-one",
"script": "index.js",
"sourceDir": "node_modules/my-service-one"
},
{
"append": true,
"uid": "my-service-two",
"script": "index.js",
"sourceDir": "node_modules/my-service-two"
}
]
And I launch it with npm start(package.json):
...
"scripts": {
"start": "node_modules/forever/bin/forever start services.json",
}
...
But when I try to make npm start, I have an error:
Error: Cannot find module '/Users/my_user/project_name/node_modules/my-service-one/node_modules/my-service-one/index.js'
WTF is this: /node_modules/my-service-one/node_modules/my-service-one? Why?
It should use /node_modules/my-service-one/index.js. So why?
UPD: What I've already try(without result):
rm -rf node_modules;
Restart;
Use node v4, v5, v6;
npm cache clean;
Find other node_modules in wrong places inside project;
Google it;
This is bad question perhaps, but I'm really didn't know why it's happens. Thanks.
Have you tried to launch this modules with forever from command line?
This path issue looks like a bug for me, I think the obvious duct-tape type fix is use absolute path in services.json instead of relative. It will look terrible but it should work.
But I think it's better to install forever globally (with -g key) and then use a simple shell script to start your services with forever (two lines with something forever start /Users/my_user/project_name/node_modules/my-service-one/index.js) - this way works fine for me.
And also it's quite easy to start this script at the boot-up, or even write a script to start and stop your modules as a service.
UPD: This also may helps: sourceDir: './'

Categories