OP EDIT: If anyone else comes across this: the app was created using create-react-app, which limits importing to within the src folder. However if you upgrade react-scripts to v1.0.11 it does let you access package.json.
I'm trying to get the version number from package.json in my app.
I've already tried these suggestions, but none of them have worked as I can't access package.json from outside the src folder (might be due to React, I'm new to this). Moving package.json into src then means I can't run npm install, npm version minor, and npm run build from my root folder. I've tried using process.env.npm_package_version but that results in undefined.
I'm using Jenkins, and I haven't set it up to push the commits up yet, but the only idea I have is to get the version from the tags in GitLab, but I have no idea how to do that, and it would add unnecessary dependency to the repo, so I would really like to find an alternative.
EDIT:
My file structure is like:
--> RootAppFolder
|--> build
|--> node_modules
|--> public
|--> src
|--> Components
|--> Root.js
|
|--> package.json
So to access package.json from Root.js I have to do import packageJson from './../../package.json' and then I get the following error:
./src/components/Root.js
Module not found: You attempted to import
./../../package.json which falls outside of the project src/
directory. Relative imports outside of src/ are not supported. You can
either move it inside src/, or add a symlink to it from project's
node_modules/.
Solving this without importing and exposing package.json to the create-react-app
Requires: version 1.1.0+ of create-react-app
.env
REACT_APP_VERSION=$npm_package_version
REACT_APP_NAME=$npm_package_name
index.js
console.log(`${process.env.REACT_APP_NAME} ${process.env.REACT_APP_VERSION}`)
Note: the version (and many other npm config params) can be accessed
Note 2: changes to the .env file will be picked only after you restart the development server
From your edit I would suggest to try:
import packageJson from '/package.json';
You could also try to create a symlink:
# From the project root.
cd src; ln -s ../package.json package.alias.json
List contents of src directory and you'll see the symlink.
ls
#=> package.alias.json -> ../package.json
Adding the .alias helps reduce the "magic" for others and your future self when looking at this. Plus, it'll help text editors keep them apart. You'll thank me later. Just make sure you update your JS code to import from ./package.alias.json instead of ./package.json.
Also, please take a look at this question:
The create-react-app imports restriction outside of src directory
Try this.
// in package.json
"version": "1.0.0"
// in index.js
import packageJson from '../package.json';
console.log(packageJson.version); // "1.0.0"
I don't think getting version by 'import' or 'require' package is correct.
You can add a script in you package.json
"start": "REACT_APP_VERSION=$npm_package_version react-app-script start",
You can get it by "process.env.REACT_APP_VERSION" in any js files.
It also works in build scripts, like this:
"build": "REACT_APP_VERSION=$npm_package_version react-app-script build",
import package.json
Generally speaking, importing package.json is not good. Reasons: security & bundle size concerns
Yes, latest webpack (default config) + ES6 import does tree-shaking (i.e. only includes the "version" value instead of the whole package.json) for both import packageJson from '../package.json' and import { version } from '../package.json'. But it is not guaranteed if you use CommonJS (require()), or have altered your webpack config, or use another bundler/transpiler. It's weird to rely on bundler's tree-shaking to hide your sensitive data. If you insist on importing package.json but do not want the whole package.json exposed, you may want to add some post-build checks to ensure other values in package.json are removed.
However the security concern here remains theoretical for open source projects whose package.json is public after all. If both security and bundle size are not problems, or, the non-guaranteed tree-shaking is good enough for you, then go ahead)
.env
The .env method, if it works, then it's good, but if you don't use create-react-app, you might need to install dotenv and do some additional configurations. There's also one small concern: it is not recommended to commit the .env file (here and here), but if you do the .env method, it looks like you will have to commit the file as it likely becomes essential for your program to work.
Best practice (arguably)
(this is not primarily for create-react-app, but you still can either use react-app-rewired or eject cra in order to configure webpack in cra)
If you use webpack, then with DefinePlugin:
plugins: [
new webpack.DefinePlugin({
'process.env.VERSION': JSON.stringify(
process.env.npm_package_version,
),
}),
]
You can now use console.log(process.env.VERSION) in your front-end program (development or production).
(You could simply use VERSION instead of process.env.VERSION, but it usually requires additional configuration to satisfy linters: add globals: {VERSION: 'readonly'} in .eslintrc (doc); add declare var VERSION: string; in .d.ts file for TypeScript)
Although it's "npm_package_version", it works with yarn too. Here's a list of npm's exposed environment variables.
Other bundlers may have similar plugins, for example, #rollup/plugin-replace.
Open your package.json file and change this line
Problem Is:
// in package.json
"scripts": {
"dev": "REACT_APP_VERSION=local REACT_APP_VERSION_NUMBER=$npm_package_version react-scripts start",
...
}
Solution is
// in package.json
"scripts": {
"dev": "react-scripts start",
...
}
Related
Consider this package.json:
{
"main": "./index.js",
"name": "#myorg/foo",
"scripts": {
"build": "babel src -d dist --delete-dir-on-start --source-maps inline --copy-files --no-copy-ignored",
"check-release": "npm run release --dry-run",
"postbuild": "cp package.json dist",
"release": "npm run build && cd dist && npm publish"
}
}
I'm trying to figure out what's the best practice in order to adjust it so it'll publish the src folder that contains ESM modules in a way that'll allow tree-shaking in the final app (CRA app).
Right now there are some issues with the above package.json:
npm publish won't behave as I'd like to - you need to use npm run release instead and that's not good as other tooling will rely on publish
To create the dist folder I'm using Babel but that doesn't feel right, is it better to use another tool instead to bundle it? My goal is the final app being able to use all imports easily (with no subpath exports, index, aliases, ...)
How would you adjust the above package.json to fullfill the above requirements?
Below are the two points answered!
npm publish won't behave as I'd like to... you need to use npm run release instead and that's not good as other tooling will rely on publish.
If you look below, you can see that Babel has been removed. Due to this, there is no need for your release script anymore.
You can just run the publish command when it is ready.
$ npm publish --access=public
Remember, this only works if you did the below!
To create the dist folder I'm using Babel but that doesn't feel right, is it better to use another tool instead to bundle it? My goal is the final app being able to use all imports easily (with no subpath exports, index, aliases, ...).
You can follow a few steps to stop using Babel and use an alternative:
In your package.json, add the following key:
{
"type": "module"
}
With this, also change require() to import, and module.exports to export. For example:
// Before...
const foo = require("#myorg/foo");
module.exports = { func };
// After...
import foo from "#myorg/foo";
export { func };
Instead of importing and exporting everything from one file, you can do that in a simpler way in package.json. You need to just add something like below:
{
"exports": {
".": "./dist/index.js",
"./feature": "./dist/feature.js",
}
}
For more information, see the documentation.
When someone downloads your module, they will import like this (like Firebase):
import index from "#myorg/foo"; // index.js
import features from "#myorg/foo/features"; // features.js
Not sure if these fully answered your question, but they might give you a starting point!
I'm playing around with Yarn 2, and I want to do something like this.
I have a monorepo of the structure:
/
packages/
shared-ts/
package.json
src/
lib*/
app-ts/
package.json
src/
lib*/
app-js/
package.json
src/
lib*/
where lib* denotes that the folder is gitignored, but is where the compiled code will live.
In this example, I have a dependency library shared-ts that is used by two apps, app-ts and app-js.
The conventional approach
The conventional approach to configuring a monorepo like this, is that in shared-ts I would have a package.json like:
"main": "lib/index.js"
"scripts" : {
"build": "tsc"
}
Where the build script will build index.js and index.d.ts into the lib folder.
When both app-ts and app-js then resolve the package, they look in the lib folder and find the index.js and in app-ts's case - the index.d.ts.
This works fine, except that the developers need to remember to run the build script if they have made changes to shared-ts in order for the changes to propagate across.
Where this could potentially become problematic is where there are many layers of dependencies.
Attempted work around 1 - point main to src/index.ts.
I can change shared-ts package.json to
"main": "src/index.ts"
"scripts" : {
"build": "tsc"
}
This generally won't work, a plain node process won't be able to parse the syntax in the .ts file (eg. the import keyword).
Potential workaround - publishConfig
So something I'm considering, but haven't tried yet is, using the publishConfig
fields in the package.json
This field contains various settings that are only taken into consideration when a package is generated from your local sources (either through yarn pack or one of the publish commands like yarn npm publish).
"main": "src/index.ts",
"publishConfig": {
"main": "lib/index.js"
}
The idea being that:
When you publish a package to npm, lib/index.js will be used as main. 👍 code is ready for consumption, no compilation required.
If being used directly in the monorepo src/index.ts will be used as main. 😕 This kind of works as if you were running app-ts with ts-node for example.
However, where this starts breaking down is:
Running app-js in a development environment (where you don't have any additional syntax parsing set up).
Practical current best solution
My current best solution is to 'just give up on this 'no compile' aspiration' - if a developer makes changes to some code, they need to re-run build for the changes to propagate across.
How about using this?:
import someValue from 'some-package/src/index';
I can do this in my monorepo like the image below
I believe using nx will be good choice here. While it won't help you run the uncompiled code, it has pretty good features. In particular, you can automatically run the affected:apps on certain changes. For example, if you have a start command, it will run the start command for all the affected apps.
I wanted the same thing but had to compromise on the "Automatic compilation on changes" option in my JetBrains IDE.
It allows me to debug with ts-node as well as run the code using the native node binary.
I am unable to import TS files that exist in my Angular project directories inside my Node server.
I've looked into various settings for a tsconfig.json file for the Node server specifically but have had no luck.
I run my node server via npm start like so "start": "nodemon --exec ts-node -- ./start.ts"
My project structure looks something like this...
....
node_modules/
src/
app/
shared/
models/
entity.model.ts
stub-server/
start.ts
src/
data/
entity-data.ts
angular.json
tsconfig.json
...
I expect to be able to import the relevent Typescript classes/interfaces/enums etc from entity.model.ts inside entity-data.ts so that I can enforce type safety within my mocked data.
You definitely need to use better tooling for your project.
Please check https://nx.dev/ and create your Angular app and Node app, move your code there, and then you will be able to create a library with your shared stuff, to be imported from both projects.
Nx will take care of the configuration and the tsconfig paths required to make it work. And talking about tsconfig.paths, you may try to setup one in your current project, perhaps this structure is not clean:
"compilerOptions": {
"paths": {
"#shared/*": ["src/app/shared/*"]
}
}
and import your stuff from your server like
import { MyModel } from '#shared/models';
Anyways, consider the migration of your code to Nx and you will be able to enjoy a clean architecture and workflow. Happy coding!
I am working on a NodeJS (v. 8.12.0, EcmaScript 6) project, whose project structure is similar to:
project_root/
src/
utils/
protocol_messages/
helpers.js
tests/
unit/
utils/
protocol_messages/
helpers.js
I am writing tests using Mocha as a test framework.
Question
In the helpers.js under tests/unit/utils/protocol_messages/, what's the proper way of importing the module-under-test?
To elaborate:
I want to avoid the relative path in: require('../../../../../src/utils/protocol_messages/helpers').
It works, but it's ugly, and if the project structure changes, I would have to rewrite the test imports, as well.
(I am new to Javascript so I might be doing several things wrong.)
Update
Solutions provided in this question:
require.main.require: in a comment to this answer, "This solution will not work if code covered with unit tests like Mocha test".
Extracting my utils to a node module doesn't make sense for me, since the code is very application specific.
Having an extra node_modules under my src/ project root of a NodeJS project doesn't seem to make sense.
Using a Javascript transpiler when I am using only features available in NodeJS and writing CommonJS projects seems a bit of an overkill.
If I am mistaken on any of the above points, please point it out, as I am at a loss. It seems to me like NodeJS doesn't not provide a native way to import CommonJS modules with absolute paths.
You can use wavy npm package.
This module lets you turn things like require('../../../../foo') into something like
require('~/foo'). The way it works is that on postinstall it creates a symlink in app/node_modules/~ to point to app/
Assume you need a config.js file present at your project's root in a file which is present at /routes/api/users/profile.js, you do not want to import it as ../../../config.js
Create a directory structure in your project's root directory as described below:
/Modules
index.js
package.json
Modules/index.js
module.exports.config = require('../config.js')
Modules/package.js
{
"name": "modules",
"main": "index.js",
"version": "1.0.0",
"dependencies": {}
}
Now run
npm install ./Modules
/routes/api/users/profile.js
const { config } = require('modules')
This way autocomplete feature of your code editor will also work. No more global variables pollution, long relative imports, no dependency on environment variables and the best part is, it will work with pm2 and nodemon.
I have read several times the documentation provided at :
Node API Babel 6 Docs
I'm starting out learning pg-promise following the Learn by Example tutorial and would prefer to work with ES6 and transpile to ES5 with Babel but am unsure of a few things :
After installing babel-core, what preset do I use and where/how do I configure this to work?
The documentation was unclear to me about which file I put: require("babel-core").transform("code", options); into and what parts of that code are place holders. When I use that code, do I just use it one time somewhere and then I can use ES6 in every other file? How would this be achieved?
I read about this .babelrc file and would like to confirm if the actual filename is ".babelrc" or if that is just the file extension and where in relation to the root directory of my project do I put that file.. and how do I link to it?
If I'm using pg-promise should I be using ES6 and Babel or will running : npm install as described under the Testing section for pg-promise be enough and trying to use ES6 with this create more problems?
I was hoping to take advantage of let and const if the need came up during my server side development.
Is there a standard file structure for a node+babel+pg-promise server setup?
Edit
Worth noting that I have also read Node JS with Babel-Node and saw that using this should be avoided. The final answer at the very bottom didn't really make sense to me for similar reasons I'm having trouble following the actual documentation provided by Babel.
1.a What Preset is needed?
You will need to install Babel firstly with npm install babel-core --save-dev in the root directory of your project using a Terminal window like Command Prompt.
Once installed, you will need to install the es2015 preset with npm install babel-preset-es2015 --save-dev. Babel-Core is Promises/A+ Compliant but not ideal for usage due to poor error handling so a library such as Bluebird should be used instead for this purpose. In order to transpile, babel-core will still need to be installed and es2015 enables ES6->ES5 transpiling so you can use fancy things like let and const etc.
1.b Where to put require("babel-core");?
instead, use require("babel-core/register"); and place it inside your Entry file typically called, "server.js". The server.js file will need to use CommonJS (ES5) exclusively.
By using the "require" statement it will apply all relevant transforms to all code being required into the Entry file and all files being required/included into those files.
You point to the Entry file inside package.json under the "main": section.
Package.json is created when you initialise the project with npm init at the root directory of your project inside the Terminal Window
One approach to this would be :
Entry File - server.js
server.js - requires {babel-core and the main ES6 file : config.js/jsx/es6/es}
config.es6 - uses ES6 and has includes(requires) for all other project files that can also use ES6 as they get transpiled by being loaded into the "config" file which is being directly transpiled by babel-core.
2. What is .babelrc?
.babelrc is the filename and should be placed in the same folder as your package.json file (normally the root directory) and will automatically "load" when babel-core is required to determine which preset(s) or plugins are to be used.
Inside .babelrc , you will need to add the following code :
{
"presets": ["es2015"]
}
3. pg-promise Testing Section
A direct quote from the developer recently answered this
You do not need to worry about steps in the Tests, use only the steps in the install. The one in tests relates to the dev dependency installation, in order to run tests. The pg-promise can work with any promise library compliant with Promises/A+ spec.
4. Standard File/Folder Structure for Server Side Projects?
There is no standard way to achieve this task as each project has unique demands. A good starting point would be to place the Entry file in the project root directory, the ES6 Config file in a "scripts" or "src" sub-folder and individual components in folders below that.
e.g.
ROOT/server.js
ROOT/src/config.es6
ROOT/src/component1/files.es6
ROOT/src/component2/files.es6
With this in place, Babel will successfully transpile all ES6 to ES5 and enable support of A+ compliant promises.
To begin using the node.js webserver This Guide provides a bit more insight and in the context of this answer the code shown would be placed into the ES6 config.es6 file and the following code would go into the Entry server.js file :
require("babel-core/register");
require("./src/config.es6");
The process for building Isomorphic web applications is different to this and would likely use things like grunt, gulp, webpack, babel-loader etc another example of which can be Found Here.
This answer is the combination of several key points provided by other answers to this question as well as contributions from experienced developers and my own personal research and testing. Thank you to all who assisted in the production of this answer.
This answer uses this simple directory structure
project/server/src/index.js => your server file
project/server/dist/ => where babel will put your transpiled file
Install babel dependencies
npm install -g babel nodemon
npm install --save-dev babel-core babel-preset-es2015
Add these npm scripts to your package.json file
"scripts": {
"compile": "babel server/src --out-dir server/dist",
"server": "nodemon server/dist/index.js
}
Create a .babelrc file in your project root directory
{
"presets": "es2015"
}
Transpile your directory with
npm run compile
Run your server with
npm run server
I think you should use a tool like grunt or gulp to manage all your "build" tasks. It will automate it for you, and you won't make errors.
In one command, you can transpile your code into babel ES2015 et start your application.
I suggest you to take a look at this simple project. (just install node_modules and launch npm start to start the app.js file)
However, if you really want to use babel manually,
.babelrc is the name of the file, you can see one in this project (redux) to have an example
.babelrc is a config file, if you want to see how it works, you can check this package.json (always redux)
There's actually no standard way that I know. You can use the project skeleton below if needed, and send pull request to improve it :-)
#makeitsimple
Step: 1
npm install nodemon --save
In project directory
Step: 2
yarn add babel-cli
yarn add babel-preset-es2015
Step: 2
In package.json-> scipts change 'start' to the following
start: "nodemon src/server.js --exec babel-node --presets es2015"
Step: 3
yarn start