mocha equivalent to webpack's resolve root - javascript

I'm writing some mocha tests that load code that have paths like this:
import MyStore from "stores/MyStore"
This works fine in the web browser because we are using the webpack-dev-server which in turn reads this entry from webpack.config.js: config.resolve.root: [path.resolve(__dirname, "./app")] so it knows to find ./app/stores/MyStore.
This path does not work when running it from mocha --compilers js:babel/register. I'm trying to locate a package or configuration that I may use for this. It would save us from having to change may code references and of course keep our imports more portable.
Not sure if it matters, we use iojs. If this really can't be done it would be fine just to update the paths. Thank you...

How about including your app directory in $NODE_PATH:
env NODE_PATH=$NODE_PATH:$PWD/app mocha ...

Here's a cross-platform method. First install cross-env:
npm install cross-env --save-dev
then in your package.json:
"scripts": {
...
"test": "cross-env NODE_PATH=./app mocha ..."
}

In windows, I had to do this:
set NODE_PATH=%CD%/app&& mocha...
for some reason, adding a space after 'app' would cause it not to work

Related

Nuxt typescript building and transpile project for deployment

I have a Vue application built with the NuxtJS framework using the yarn create nuxt-app utility.
The application is meant to be for Server-Side-Rendering meaning it has to run on an actual server instance.
I am using Nuxt-ts to be able to use typescript with Nuxt, my nuxt.config.js looks like this:
export default {
ssr: true,
srcDir: 'src/',
buildModules: [
// https://go.nuxtjs.dev/typescript
'#nuxt/typescript-build',
// https://go.nuxtjs.dev/stylelint
'#nuxtjs/stylelint-module',
],
server: {
port: envsConfig.env.ENV_CP_HTTP_PORT || 2055,
}
}
When building using nuxt-ts build, I get a folder .nuxt with the results of the build phase,
My scripts are:
"scripts": {
"dev": "nuxt-ts",
"build": "nuxt-ts build",
"start": "nuxt-ts start"
}
The question now, how can I deploy this on a server and run it using node?
Cuz running node .nuxt/dist/server/server.js doesn't seem to work, and I got confused.
Also, nuxt-ts seems to transpile in runtime, where I want my application to be built+transpiled then copy the results and run them using node,
Any help would be awesome!
Thanks
First, nuxt-ts isn't mandatory. It's only useful for .ts files not compiled by webpack (typically the nuxt.config.ts). If you have nuxt.config.js in vanilla javascript, you can stay with the standard nuxt binary (no the nuxt-ts).
But you can keep it if you want. I'm just saying it's not mandatory for nuxt in Typescript.
That say, run nuxt build, and it will bundle everything you need for production inside .nuxt folder.
All you have to do then is publish this folder, and run nuxt start to run the production server :)

Typescript: Make tsconfig emit one folder but not the other folder

I'm converting an existing project from js to typescript. I want to be able to set noEmit = true on one folder but have the other folder have noEmit = false.
The reason is that I have my client(angular) code set up through webpack and do not need typescript to generate the javascript for me. While the server (Node/express) still needs to be generated into javascript.
I've tried a few different combinations but haven't seem to find the right way to do it.
My only solution that I've been able to get to work is having two tsconfig.json and running a command like tsc -p src\server\tsconfig && tsc -p src\client\tsconfig
I realize that this is not a good solution, but I have not gotten a single tsconfig to work nor having a base tsconfig.
Here is the folder structure..
|-Src
|--/client
|--/server
Is there a way to achieve this using a single tsc command? Or is there a better way I should be formatting the project? Thanks!!
I don't think there's another solution besides having multiple tsconfig.json files like you're already doing, as per this answer and this comment.
You can make this a little more streamlined by having a tsconfig.json for compilation and a separate tsconfig-build.json that you use in your package.json for building, i.e.:
// package.json
{
"scripts": {
"build": "tsc -p tsconfig-build.json"
},
// ...
}
With this setup (assuming the default tsconfig.json is in your root), running tsc from the command line will use the default tsconfig.json, but running npm run build will use tsconfig-build.json. You can also have one tsconfig extend from another, so if you have a lot of options in common, you could add a tsconfig-base.json that both configs extend from.
You can probably achieve what you want with the exclude property in your tsconfig.json file.
Check the documentation
for the exclude property

Node.js Babel build and npm module-alias

I'm using module-alias for my Node.js + Express.js project, running it with Babel for ES2015 support.
App works perfect when started with babel-node, however, if I first build it with babel (from package.json):
"build": "babel ./app --out-dir ./app_dist"
And then start:
"start": "node ./app_dist/bin/www"
It obviously cannot find the correct path specified with module-alias. Instead of looking into app_dist, Node.js searches for import in app, finds ES2015 import directive which it does not understand and throws:
SyntaxError: Unexpected token import
If I change aliases before start of that build, from app to app_dist, it works, but the question is, how to map those aliases (or how to use different _moduleAliases configuration) so that app resolves the paths correctly on development and production?
Maybe there is another way to alias modules with such stack? Thanks in advance.
Found solution for this issue.
In order to set the relative path aliases with module-alias, they shoul be defined not in package.json, but in JavaScript file inside the root directory that will be transpiled with Babel.
In my case, creating an aliases.js script inside config directory like this:
import path from 'path';
import moduleAlias from 'module-alias';
moduleAlias.addAlias('#root', path.resolve(__dirname, '../../'));
Will result in path resolving relatively to the current working directory, solving described problem.

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: './'

Why is process.env.NODE_ENV undefined?

I'm trying to follow a tutorial on NodeJS. I don't think I missed anything but whenever I call the process.env.NODE_ENV the only value I get back is undefined. According to my research the default value should be development. How is this value dynamically set and where is it set initially?
process.env is a reference to your environment, so you have to set the variable there.
To set an environment variable in Windows:
SET NODE_ENV=development
on macOS / OS X or Linux:
export NODE_ENV=development
tips
in package.json:
"scripts": {
"start": "set NODE_ENV=dev && node app.js"
}
in app.js:
console.log(process.env.NODE_ENV) // dev
console.log(process.env.NODE_ENV === 'dev') // false
console.log(process.env.NODE_ENV.length) // 4 (including a space at the end)
so, this may better:
"start": "set NODE_ENV=dev&& node app.js"
or
console.log(process.env.NODE_ENV.trim() === 'dev') // true
For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:
NODE_ENV=development node server.js
Easier, no? :)
We ran into this problem when working with node on Windows.
Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.
var environment = process.env.NODE_ENV || 'development';
In a production environment, we would define it per the usual methods (SET/export).
You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.
In the project root, run:
npm install cross-env
Then in your package.json, under scripts, add:
"start": "cross-env NODE_ENV=dev node your-app-name.js"
Then in your terminal, at the project root, start your app by running:
npm start
The environment variable will then be available in your app as process.env.NODE_ENV, so you could do something like:
if (process.env.NODE_ENV === 'dev') {
// Your dev-only logic goes here
}
in package.json we have to config like below (works in Linux and Mac OS)
the important thing is "export NODE_ENV=production" after your build commands below is an example:
"scripts": {
"start": "export NODE_ENV=production && npm run build && npm run start-server",
"dev": "export NODE_ENV=dev && npm run build && npm run start-server",
}
for dev environment, we have to hit "npm run dev" command
for a production environment, we have to hit "npm run start" command
In macOS for those who are using the express version 4.x.x and using the DOTENV plugin, need to use like this:
After installing the plugin import like the following in the file where you init the application:
require('dotenv').config({path: path.resolve(__dirname+'/.env')});
In the root directory create a file '.env' and add the varaiable like:
NODE_ENV=development
or
NODE_ENV = development
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
In UBUNTU use:
$ export NODE_ENV=test
install dotenv module ( npm i dotenv --save )
require('dotenv').config() //write inside the file where you will use the variable
console.log(process.env.NODE_ENV) // returns value stored in .env file
Must be the first require in app.js
npm install dotenv
require("dotenv").config();
In my case, I have a node app. The way I have structured it is that I have client folder and server folder. I had my .env file inline with these two folder. My server file needs the .env file. It was returning undefined because it did not live inside the server file. It was an oversight.
App
-client
-server
-.env
Instead I moved .env inside server file like so:
App
-client
-server
|-.env <---here
|-package.json
|-and the rest of the server files...
(before this - ofcourse have the dotenv npm package installed and follow its doc)
It is due to OS
In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:
"scripts": {
"start": "node app.js",
"dev": "nodemon server.js",
"prod": "NODE_ENV=production & nodemon app.js"
}
For windows
Also set up your .env file variable having NODE_ENV=development
If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)
const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' });
You can use the dotenv package from npm, here is the link: https://www.npmjs.com/package/dotenv
Which allows you to place all your configuration in a .env file
If you faced this probem in React, you need react-scripts#0.2.3 and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.
For me, the issue was that I was using the pkg library to turn my app into an executable binary. In that case, the accepted solutions didn't work. However, using the following code solved my problem:
const NODE_ENV = (<any>process).pkg ? 'production' : process.env.NODE_ENV;
I found this solution here on GitHub.
In Electron Js
"scripts": {
"start": "NODE_ENV=development electron index.js",
},
If you define any function with the name process then that may also cause this issue.
Defining process.env.NODE_ENV in package.json for Windows/Mac/Linux:
Here's what worked for me on my Mac (MacBook Pro 2019, 16 inch, Big Sur):
"scripts": {
"build": "export NODE_ENV=prod || set NODE_ENV=prod&& npx eslint . && node --experimental-json-modules ./backend/app.js && gulp",
},
Using the export NODE_ENV=prod || set NODE_ENV=prod&& string may work in Windows and Linux but I haven't tested that.
If someone could confirm that would be great.
Unfortunately using the cross-env npm package did NOT work for me at all in my package.json file and I spend a long time on my Mac trying to make this work.
I also faced this issue.
I moved .env file to the root folder (not the project folder, a level higher) and it worked out.
Check it. it might help you as well
You can also set it by code, for example:
process.env.NODE_ENV = 'test';

Categories