NPM installing modules to application root - javascript

I messed something up and I've done my best to fix it, but no luck.
Whenever I run 'npm install' on a new node project, it installs all of my dependencies to the root of the application instead of in /node_modules/ like you'd expect in a default application.
For example-
My package.json
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x"
}
}
When I use 'npm install' I end up with this:
I've tried setting my PATH like in this solution:
How to use package installed locally in node_modules?
but that didn't seem to do much. Help?

observe that you have the cache variable set in that directory
strict-ssl = false
userconfig = /private/tmp/timothy/timothy_local_job_1367532952281_60137/.npmcfg
cache = /Users/tomhorton/Documents/Repository/helpmestackoverflow
root = ./node_modules
That timothy stuff is from a module that I installed shortly before everything went haywire-
I removed that stuff and the defaults took over. Everything works great!

Related

Angular Doesn't Recognize karma.conf.js

In a commercial project, tests have been running fine for some time. We cut a release in Angular 8. On master, we upgrade to Angular 9. Now the release needs a hotfix, so I check the branch out and run tests. This is all in the same repo / file system directory.
It fails like Angular core has no exported member ɵɵFactoryDef and I quickly determine that the error is due to CLI version incompatibility.
So I uninstall ng CLI globally and reinstall npm i -g #angular/cli#8.2.0, in line with the release branch package.json. Now the above error is gone, but when I try to ng test the CLI insists that karma.conf doesn't exist. The only issue is that, like, it totally does exist.
Other things I have tried:
rm -rf and npm i from scratch
npm cache verify
close and re-open terminals
restart computer
create a new karma.conf with a different name and point angular.json to that
ng cli does respect angular.json in that the below error will change depending on my karma file name and path, but it still continues to insist, on MacOS, that the below file doesn't exist:
On Mac, I still get:
ERROR [config]: File /Users/<various paths that totally exist>/src/karma.<tried different things here>.js does not exist!
Any ideas? Thanks!!
--- Edit: adding some technical info below per request.
test block from angular.json:
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"codeCoverage": true,
"karmaConfig": "src/karma.conf.js",
"scripts": ["node_modules/jquery/dist/jquery.js", "node_modules/jquery-mockjax/dist/jquery.mockjax.js"],
"assets": [
"src/favicon.ico",
{
"glob": "**/*.html",
"input": "./src/legacy",
"output": "./"
}
]
}
}
Partial client folder structure. Notice that storybook/ and test/ are siblings of src/, and angular.json is one level above `src/. I have already tried some karma path mutations including:
"karmaConfig": "./src/karma.conf.js",
"karmaConfig": "../../<correct folders>src/karma.conf.js",
"karmaConfig": "src/karma.<change this>.js",
You might have gone through this check already but have you tried updating your package.json to have the path of karma.conf like so...?
"scripts": {
"test": "karma start ./path_to_karma.conf.js"
}
This ended up solving it for me, after steps mentioned in the question:
Delete the entire repo
Re-clone (actually, I did a shallow clone git clone <repo-url>.git --branch <ng8-branch> --depth 5
Install again npm i
Now ng test works as expected.

Why can't a peerDependency be imported or required, even when it's present in the parent module?

I'm trying to use npm peerDependencies but nothing seems to work as advertised. What am I missing?
The setup is, I have two modules, mod and plugin, both of which depend on an external module from npm. mod declares a hard dependency on both plugin and the external module, and the plugin declares a peer dependency, in order to get access to the version being used by the parent module.
The files look like this:
~/plugin/package.json:
{
"name": "plugin",
"version": "1.0.0",
"main": "index.js",
"peerDependencies": {
"pad-right": "^0.2.2"
}
}
~/plugin/index.js
var peerDependency = require('pad-right')
module.exports = 'this is a plugin'
~/mod/package.json:
{
"name": "mod",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"pad-right": "^0.2.2",
"plugin": "../plugin"
}
}
~/mod/index.js:
var hardDependency = require('pad-right')
var plugin = require('plugin')
As I understand it from docs and examples, I think this should be a standard way to use peer dependencies, and running npm install in either directory doesn't give any errors or warnings.
However when I run webpack in the mod folder, I get errors like:
ERROR in ../plugin/index.js
Module not found: Error: Can't resolve 'pad-right' in '~/plugin'
# ../plugin/index.js 1:21-41
# ./index.js
What's going wrong here, shouldn't webpack resolve the require statement inside plugin with the peer dependency from the parent mod module?
Gah, it looks like this is an edge case that only affects modules that are referencing each other locally via the file system.
The solution is apparently to add something like:
resolve: {
alias: {
'pad-right': path.resolve('node_modules', 'pad-right'),
},
},
to your webpack config. (Or else to try resolve.symlinks: false, which solves the problem in the minimal repro code I posted, but doesn't solve things in my actual project).
Article about the issue

How can I export a React Component as an NPM package to use in separate projects?

I have created a React component inside a project that I'd like to use in multiple projects. At the moment, I only care about doing this locally and for development. The React Component is rendered into the root div, the project uses webpack and babel to transpile JSX, ES6 and some ES7 features into a bundle.
I thought it would be simple to export this component such that I can simply run npm install MyComponent and begin using it in a fresh project. However, I find it isn't so straight forward. In particular, I've been reading for hours and hours and only seem to be getting more confused.
If my end goal is to keep developing 'MyComponent' in its containing project, while using 'MyComponent' in any number of other local projects, what are my options? The first thing I did was change the main key of my package.json to /src/components/MyComponent and run npm pack. This produces a tgz file I can install via its absolute filepath in other projects. However, I found that the es6 and jsx was not being transpiled and so my client projects would be unable to parse MyComponent. I then used webpack to transpile into lib/MyComponent, but when I have import MyComponent from './path/to/MyComponent-1.0.0.tgz I'd only see {} (an empty object) in the console.
Searching for solutions to my problem turn up many different approaches pulling together NPM, Grunt, Gulp, Babel, Webpack, etc.. And I am worried it will be many many more hours (days?) before I can grind that down to something understandable.
Given my requirements, what is the simplest solution I can implement to 1) compile down my React Component to the simplest to import module 2) import it into any local projects 3) continue to develop the package in the original host project and have changes easily propagate to client projects.
In general, if you're going to begin creating React components as separated packages (which is a great pattern, for all the reasons you've already mentioned) - you're going to need to get at least a bit familiar with webpack and babel. There's a ton to learn here, but let me try to point you in the right direction:
// webpack.config.js
/* eslint-disable */
const path = require('path')
const webpack = require('webpack')
const ENVIRONMENT = process.env.NODE_ENV
const PRODUCTION = ENVIRONMENT === 'production'
const SOURCEMAP = !PRODUCTION || process.env.SOURCEMAP
const library = 'your-lib-name' // << RENAME THIS <<
const filename = PRODUCTION ? `${library}.min.js` : `${library}.js`
const plugins = []
if (PRODUCTION) {
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(ENVIRONMENT),
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
output: { comments: false, semicolons: false },
sourceMap: SOURCEMAP,
})
)
}
module.exports = {
devtool: SOURCEMAP ? 'source-map' : 'none',
entry: `${__dirname}/path/to/your/component.js`, // << RENAME THIS <<
externals: {
'react': 'react',
'react-dom': 'react-dom',
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}],
},
output: {
filename,
library,
path: `${__dirname}/lib`,
libraryTarget: 'umd',
umdNamedDefine: true,
},
plugins,
}
I know that looks like a bunch - but it handles the majority of what you're going to want. In specific:
If you specify NODE_ENV=production when building, this will uglify/minify your package, and do some other trimming which you may want later.
Building with this script will output a sourcemap, which you can use with dev tools to inspect your minified code in the debugger window, among other things.
This marks react and react-dom as externals - which means they won't get bundled up and packaged inside your bundle. This is great - because it means you won't get 2+ copies of react's filesize just because you've imported your own component!
To use it, though, you now need some package.json love.
package.json
{
"name": "Your Name",
"version": "0.0.1",
"description": "This is my awesome react package!",
"main": "path/to/your/component.js",
"author": "Your Name",
"license": "MIT",
"repository": { /* Your Repo Info Here */ },
"dependencies": {
"any-packages-you-need-included-in-builds": "^1.0.0"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-loader": "^7.1.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"prop-types": "^15.5.10",
"react-dom": "^15.6.1",
"webpack": "^3.0.0"
},
"scripts": {
"build": "yarn prebuild && NODE_ENV=production webpack",
"prebuild": "mkdir -p ./lib && rm -rf ./lib/*"
}
}
Obviously, you can have a lot more here if you need it - such as other babel-plugin-* plugins that you use in your transpilation, other packages, etc.But this set will let your webpack build run. Note that the scripts here assume you're using yarn - so that you can run yarn build, and that you're on a posix system, for mkdir to work. If you're on windows or not using yarn, just update the scripts accordingly.
The rest is just learning to publish your package to npm or another package repository. Primarily, that's just setting the version number in package.json to something new (npm version) and then publishing (npm publish). You will have to have an npm account for this, of course - and be logged in (npm login).
Once you've published to npm you can just yarn add your-package-name.
Remember, though - we marked react and react-dom as external - so in the consuming package, you'll need to make sure they're available as window.React and window.ReactDOM - or you'll need to include the component directly from node_modules/your-package-name/path/to/your/component.js
You don't need to npm pack a package to use it. If you make your component into a git repo and put it on Github, you can use NPM to install it directly from Github by using npm install alex/mycomponent where alex is your github username and mycomponent is the repo name. Re-running that command will re-install from Github, in case you make changes to the repo.
Once you're happy with the component, you can upload it to the NPM registry to install like any other package (npm install name). Using Github at first makes it a bit easier to develop.
Webpack might not compile things from node_modules by default. Usually, packages are pre-compiled before being published anyway, but you should be able to configure webpack to build your 'packaged' component, along with the rest of your app. Maybe this will help: https://stackoverflow.com/a/38008149/7486612
In order to push react libraries into NPM, you may need some boilerplate which will install and convert many things for you (and you can still use your current react module as the main source, just follow the guides at the end of my answer, then you will surely get all the ideas)
Or you can also refer to my previous answer to a similar question:
Issue with publishing to npm
=====
I've also pushed several react libraries successfully into NPM:
https://www.npmjs.com/~thinhvo0108
=====
Your github repositories' folder structure should also look like mine:
https://github.com/thinhvo0108/react-paypal-express-checkout
=====
Useful tutorial below here:
(boilerplate source) https://github.com/juliancwirko/react-npm-boilerplate
(author's article) http://julian.io/creating-react-npm-packages-with-es2015/
Start by looking at existing component library, eg Material UI.
Specifically check out npm scripts they have (see package.json):
"build:es2015": "cross-env NODE_ENV=production babel ./src --ignore *.spec.js --out-dir ./build",
"build:es2015modules": "cross-env NODE_ENV=production BABEL_ENV=modules babel ./src/index.js --out-file ./build/index.es.js",
"build:copy-files": "babel-node ./scripts/copy-files.js",
"build:umd:dev": "webpack --config scripts/umd.webpack.config.js",
"build:umd:prod": "cross-env NODE_ENV=production webpack --config scripts/umd.webpack.config.js",
"build": "npm run build:es2015 && npm run build:es2015modules && npm run build:copy-files && npm run build:umd:dev && npm run build:umd:prod",
That's example of very involved and high quality component library, that makes sure that regardless of your build pipeline you'll be able to use it.
Setting up build process with webpack might be cumbersome, but don't concentrate on that too much from the begining, and cover cases that are most straight forward to you.
Also check out https://storybook.js.org/ while working on your components.

Issue with permissions in a node.js module

I built an npm module named emeraldfw and published it. My package.json file is
{
"name": "emeraldfw",
"version": "0.6.0",
"bin": "./emeraldfw.js",
"description": "Emerald Framework is a language-agnostig web development framework, designed to make developer's lives easier and fun while coding.",
"main": "emeraldfw.js",
"directories": {
"example": "examples",
"test": "test"
},
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/EdDeAlmeidaJr/emeraldfw.git"
},
"keywords": [
"web",
"development",
"framework",
"language",
"agnostic",
"react"
],
"author": "Ed de Almeida",
"license": "MIT",
"bugs": {
"url": "https://github.com/EdDeAlmeidaJr/emeraldfw/issues"
},
"homepage": "https://github.com/EdDeAlmeidaJr/emeraldfw#readme",
"devDependencies": {
"jshint": "^2.9.4",
"mocha": "^3.3.0"
},
"dependencies": {
"jsonfile": "^3.0.0",
"react": "^15.5.4",
"vorpal": "^1.12.0"
}
}
As you may see, I declared a "bin": "./emeraldfw.js" binary, which corresponds to the application itself. The package.json documentations says this is going to create a link to the application executable at node.js bin/ directory. This worked fine, but when I install it globally (npm install emeraldfw -g) and then run it from the command line I receive an error messsage
All other node modules are working fine and my application is passing in all tests and when I run it directly inside the development directory (with node emeraldfw.js) it works really fine.
I'm not a node.js expert and after having fought this error for two days, here I am to ask for help.
Any ideas?
EDIT:
I checked the permissions for my node binary (emeraldfw.js) and it belongs to edvaldo:edvaldo, my user and group. And it is with executable permissions set. I should have no permission issues inside my own area with these settings, don't you think?
Well, shebang issue here.
Before creating npm modules, you need read every single line of it's documentation.
As it stated here you need to use shebang to let your operating system know that it should run with node instead of operating system's own script execution hosts.
Please make sure that your file(s) referenced in bin starts with
#!/usr/bin/env node, otherwise the scripts are started without the node executable!
So, by using shebang on an npm module, you tell the os to create platform specific executables which let it use node to run the script. A .cmd file on Windows for example.
Have you try to install as su?

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