Regular expression to match a module in a package.json content - javascript

I'm trying to dynamically add and remove modules from a package.json file programmatically. To achieve this, I need a regular expression that can match a particular module in the devDependencies or dependencies.
Here is what I've tried
const packageJsonContent = "my package.json content read from a file";
const moduleName = "babel"; //an example module to be removed from `packageJsonContent`
let moduleRegex = new RegExp('"\\s*'+moduleName+'\\s*"\\s*:\\s*".*"(\s*,)?'); //<-- I need help here
//remove module
packageJsonContent.replace(moduleRegex, "");
The issue with my approach is that; if there's any key out of the devDependencies or dependencies section but has the same name as the moduleName, the regular expression will match it.
My request
I need a regular expression that will match a given module found under the dependencies or devDependencies sections of a package.json file. Thanks

Consider parsing the JSON instead, and delete the [moduleName] property from the dependencies and devDependencies objects, rather than using a convoluted regular expression:
const moduleName = "babel";
const packageJSONStr = `{
"name": "somename",
"scripts": {
"build": "tslint src/**/*.ts && webpack"
},
"author": "bob",
"dependencies": {
"foo": "^1.2.3"
},
"devDependencies": {
"babel": "^1.2.3",
"ts-loader": "^6.2.1",
"typescript": "^3.6.3",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9"
}
}`;
const packageJSON = JSON.parse(packageJSONStr);
delete packageJSON.dependencies[moduleName];
delete packageJSON.devDependencies[moduleName];
console.log(packageJSON);

You can find your dependencies and devDependencies sections first, then remove your desired modules from them, then replace your new dependencies or devDependencies in the package.json file.

Related

nodejs - pkg Error! Not more than one entry file/directory is expected

I have a simple cli node script that I want to pack using pkg.
I've tried with the following command
host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64
unfortunately I will get this error in terminal
> pkg#4.4.9
> Error! Not more than one entry file/directory is expected
If I try to remove the target instead, I will get this other error in terminal
> pkg#4.4.9
> Targets not specified. Assuming:
node15-linux-x64, node15-macos-x64, node15-win-x64
> Error! No available node version satisfies 'node15'
In my system I'm running node v15.4.0 so I can't understand what's wrong.
My project package.json file looks like:
{
"name": "myscript",
"version": "1.3.0",
"bin": "index.js",
"dependencies": {
"chalk": "^4.1.0",
"commander": "^7.1.0",
"dotenv": "^8.2.0",
"facebook-chat-api": "^1.8.0",
"forever-monitor": "^3.0.3",
"node-notifier": "^9.0.0"
}
}
How I can pack my app and fix these problems?
Seems like you're missing an s : use --targets instead of --target
pkg can generate executables for several target machines at a time. You can specify a comma-separated list of targets via --targets
https://www.npmjs.com/package/pkg

node module not found after copying only dependency modules with gulp-npm-dist

I am trying to find the best way to package only the node_modules dependencies that my project needs. So I found gulp-npm-dist and have a gulpfile.js
var gulp = require('gulp');
var npmDist = require('gulp-npm-dist');
gulp.task('CopyNodeDependencies', function() {
gulp.src(npmDist(), {base:'./node_modules'})
.pipe(gulp.dest('./node_dependencies'));
});
this places just the modules i need from my package.json:
{
"version": "1.0.0",
"name": "common",
"private": true,
"devDependencies": {
"gulp": "^3.9.1",
"gulp-less": "^3.1.0",
"gulp-npm-dist": "^0.1.2",
"gulp-rename": "^1.2.2",
"pump": "^1.0.1"
},
"dependencies": {
"chart.js": "^2.7.3",
"chartjs-node-canvas": "^2.0.1",
"moment": "^2.24.0"
}
}
but when I run my node file that has var moment = require('moment'); at the top it says cannot find module moment. I have renamed node_dependencies to node_modules and it still throws this error. I have also tried relative paths like ./node_dependencies/moment and that still doesnt work.
here is the folder structure of the node_dependencies if that helps:
You have to leave original node_modules directory as is to use require().
gulp-npm-dist copies only minified files without package.json, yarn.lock etc.

Cannot resolve module while trying to organize modules in React Native

I'm new to React Native and am trying to organize my React Native classes into modules to get rid of the "import from '../../../" mess. Here's my very simple folder structure:
Following the tutorial at here, I've structured my package.json as this for each folder:
{
"name": "#foldername"
}
Now, I'm trying to import Page (which is just a component superclass at this time, exported as default in the file):
import Page from '#app/components/core';
But it cannot be resolved. I've also tried:
import Page from '#app/#components/#core';
import { Page } from '#app/#components/#core';
import { Page } from '#app/components/core';
import { Page } from 'app/components/core';
None of them seem to be working. I've also tried them all without the # sign (removing it from both the package files and import statement), but no avail.
How can I organize my components to work that way (and it would be great if I knew what that # sign in front does, as I've also seen some tutorials without it)?
Here is my package.json in my root folder if it helps (haven't touched it, it's the way created by react-native init):
{
"name": "redacted",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.3"
},
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/runtime": "^7.4.2",
"babel-jest": "^24.5.0",
"jest": "^24.5.0",
"metro-react-native-babel-preset": "^0.53.1",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native"
}
}
add babel-plugin-module-resolver to devDependencies.
If you have .babelrc just delete it and add babel.config.js. And add aliases there. It should look like this
function babelConfig(api) {
if (api) {
api.cache(false);
}
const presets = ['module:metro-react-native-babel-preset'];
const plugins = [
[
'module-resolver',
{
alias: {
appColors: './src/Colors',
appConstants: './src/Constants',
components: './src/Components',
screens: './src/Screens',
utils: './src/utils'
},
cwd: 'babelrc'
}
]
];
return {
presets,
plugins
};
}
module.exports = babelConfig;
Then you can use import like this
import { YourComonent } from 'components';
make sure you have exported as default.
Also, don't try to set the alias names with capital letters
This works with the latest react-native (0.59.3).
Here is my devDependencies
devDependencies": {
"#babel/core": "7.4.0",
"#babel/runtime": "7.4.2",
"#react-native-community/eslint-config": "0.0.3",
"babel-eslint": "8.2.2",
"babel-jest": "24.5.0",
"babel-plugin-module-resolver": "^3.2.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.10.0",
"enzyme-to-json": "^3.3.5",
"eslint": "5.15.3",
"eslint-config-airbnb": "16.1.0",
"eslint-plugin-import": "2.12.0",
"eslint-plugin-jsx-a11y": "6.0.3",
"eslint-plugin-react": "7.9.1",
"eslint-plugin-react-native": "3.2.1",
"jest": "24.5.0",
"metro-react-native-babel-preset": "0.53.1",
"react-test-renderer": "16.8.3"
},
If you're using VSCode, Intellisense of the IDE does not recognise just the package.json; include a tsconfig/jsconfig JSON file (TypeScript [ftw]/ JavaScript)
In compilerOptions add :
"paths" : {
"#alias1*" : ["./alias1/*"],
.....
}
For all your aliases. Then the editor should pick up your files.
https://code.visualstudio.com/docs/languages/jsconfig
If you choose not to use VSCode, use Babel:
If your project doesn’t use Webpack - for example if you’re working with React Native, you can use your .babelrc file and a babel plugin to get aliasing set up.
Firstly, you’ll want to install babel-plugin-module-resolver with yarn or npm.
Once you’ve done that, open up your project’s .babelrc file, and under the plugins key, add this:
[
'module-resolver',
{
root: ['./src'],
alias: {
myAlias: './src',
},
},
];
Or use the package.json in root
It was my bad.
Instead of using it like:
import MyComponent from 'package/path/MyComponent'
I was using:
import MyComponent from 'package/path' (without my class file at the end).
I've imported it correctly (also removed the app package and the # prefixes and directly referenced components as a package in its package.json file) (including the component name):
import Page from 'components/core/Page';
It worked perfectly.
In tsconfig.json, add the following :
"compilerOptions": {
"baseUrl": "app"
...
}

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.
Please update your configuration.
I found this exact question here: setupTestFrameworkScriptFile is not supported error
I renamed my jest.config.js to setUpTests.js however that did not remove the deprecated error warning.
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
package.json scripts
"scripts": {
"dev": "next -p 7777",
"build": "next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --watch --no-cache",
"test-win": "SET NODE_ENV=test&& jest --watch"
}
"#types/enzyme": "^3.1.15",
"#types/jest": "^23.3.13",
"jest": "^24.1.0"
Jest used to have a config option called setupTestFrameworkScriptFile...
...but it was deprecated in favor of the newer setupFilesAfterEnv in PR #7119 which shipped with version 24.0.0.
Since you are using Jest ^v24.1.0 you will need to use setupFilesAfterEnv.
Just find where setupTestFrameworkScriptFile is used in your Jest config, rename it to setupFilesAfterEnv, and put the single file it used to point to in an array and you should be good to go.
Example, change this jest.config.js:
module.exports = {
...
setupTestFrameworkScriptFile: './setup.js',
...
}
...to this:
module.exports = {
...
setupFilesAfterEnv: ['./setup.js'],
...
}
If you are using create-react-app, change the key name at package.json file
from
"jest": {
// ...
"setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js",
to
"jest": {
// ...
"setupFilesAfterEnv": ["<rootDir>/src/setupTests.js"],
After I changed my file name from setupTests.js to setup.tests.js it worked. Maybe the dir path name did not match. Make sure you check that!
In my case in 'jest.config.js' I had
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
correctly referencing 'setup-jest.ts' in <rootDir>.
After renaming the file itself and the reference to it from
setup-jest.ts
to
setupJest.js
the error message vanished. Weird. Seems as if the hyphen in the file-name or being the same as in 'node_modules.jest-reset-angular.setup-jest.js' was the culprit.
Using Angular 13 and Jest (in package.json):
"jest": "^28.1.0",
"jest-preset-angular": "^12.1.0",
I'm on Lubuntu 22.04.
Jest message is not mantained anymore: https://github.com/mattphillips/jest-expect-message/issues
So I suggest using:
const msg = '... my message...'
expect({msg, result}).toEqual({msg, result: expected})
From https://github.com/facebook/jest/issues/3293
Or alternatively
function expectToBeTrue(result: any, message: string){
return expect({message, result}).toBe({message, result: true})
}
expectToBeTrue(compute() == 1, "Oh no compute should return 1!")

Bower is only downloading bower.json but no real dependancy files

My bower.json:
{
"name": "best-project-ever",
"version": "0.0.0",
"dependencies": {
...
"xdomain": "0.6.11"
},
"devDependencies": {}
}
Running bower install, or bower install xdomain creates:
app/
bower_components/
xdomain/
bower.json
But nothing else! The bower.json file for xdomain clearly specifies including xdomain.js and xdomain.min.js (ignoring everything BUT those files), but neither file is downloaded by bower. Any ideas? =)
{
"name": "jpillora/xdomain",
"version": "0.6.10",
"main": "dist/0.6/xdomain.js",
"license": "MIT",
"ignore": [
"*",
"!bower.json",
"!dist/0.6/xdomain.js",
"!dist/0.6/xdomain.min.js"
],
"dependencies": {},
"devDependencies": {}
}
bower.json spec says, that they are using the exact same syntax as .gitignore-files.
.gitignore does specify the "!" as follows:
An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. It is not possible to re-include a file if a parent directory of that file is excluded.
Note the bold sentence, which is exactly the problem.

Categories

Resources