Published npm package doesn't show function hints - reactjs

I have a utils function inside my published npm package that exports many functions, The functions look like this:
const createBox = ({id, width}) => {
}
Before I publish my npm package, When I enter createBox, I can see all parameters it can take but After I publish my npm package and Install it in another project, I don't get any hints and After hovering over the function All I see is an Any word.
I'm using ReactJS, my babel.config.json file:
{
"presets": [
[
"#babel/env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
],
"#babel/preset-react"
]
}
And here is the build:
"build": "cross-env NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__",
How can I build the package so It shows all the function hints including its parameters?.

I'm assuming you are using VSCode? I think this is some annoying default. Try changing this setting in VSCode:
"javascript.implicitProjectConfig.checkJs": true

Related

React compiler end up with Unexpected token <

I am beginner in React and I am struggling with compiler error. Let me introduce my situation. I have two independent React applications:
App A - Big ERP
App B - "Plugin" to the App A
I supposed I will develop App B as an independent application. Then, I will install it to the App A (using npm install git#github.repo/...) once I finish development of the App B. I expected I will call components from App B within the App A source code. Everything went fine until I run the compilation. I am receiving:
SyntaxError: /frontend/node_modules/connector_frontend/src/views/Connector/FormView/index.js: Unexpected token
In my /frontend/node_modules/connector_frontend/src/views/Connector/FormView/index.js there is following code:
const ConnectorFormView = ({ AppValues, secureFetch, ...rest }) => {
return (
<p>Hello world</p>
)
}
export default ConnectorFormView;
Error is ocuring at the position of <p>.
I call this functional component from App A (frontend/src/views/Connector/ConnectorNewEditView/index.js) like this
import ConnectorFormView from "connector_frontend/src/views/Connector/FormView";
const ConnectorNewEditView = () => {
return (<ConnectorFormView AppValues={appValues} secureFetch={secureFetch} />)
}
export default ConnectorNewEditView;
I tried to return just a plain text from the ConnectorFormView component like this:
const ConnectorFormView = ({ AppValues, secureFetch, ...rest }) => {
return (
'Hello world'
)
}
export default ConnectorFormView;
and it was compiled successfully, but once I return a JSX from the ConnectorFormView component the compiler get crashed.
Can anyone explain the source of this error please?
I successfully figured out the source of this problem and also I found a solution. I expected I can reuse however React component implemented in JSX. I expected, the only requirement is to install it, resp. download it in JSX form to my project using NPM. It's FALSE.
According to my research, I can reuse React components compiled from JSX to ES only. It is achievable using Babel. Another very important requiremen, it should not by installed as React application as I installed it. It must be installed as a NPM package with clearly defined set of exported components.
I found this paper https://levelup.gitconnected.com/publish-react-components-as-an-npm-package-7a671a2fb7f and I followed it step by step and finally I achieved desired result.
I can very briefly mention steps which I performed:
Implemented my custom component (mentioned above)
const ConnectorFormView = ({ AppValues, secureFetch, ...rest }) => {
return (
<p>Hello world</p>
)
}
export default ConnectorFormView;
Added the component to /src/index.js file in order to export it for host App
import ConnectorFormView from './components/ConnectorFormView';
export { ConnectorFormView };
Installed Babel and all needed presets
npm install --save-dev #babel/core #babel/cli #babel/preset-env
npm install -save #babel/polyfill
configured Babel - created file /babel.config.json with following content
{
"presets": [
[
"#babel/env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
],
"#babel/preset-react"
]
}
Added new script to the package.json to compile React components to ES:
"build": "rm -rf dist && NODE_ENV=production babel src --out-dir dist --copy-files";
Executed npm run build to compile React components to ES. Compiled components are located in new dist folder.
Adjusted package.json that looks like this now
{
"name": "my_react_components",
"version": "0.1.0",
"private": true,
"description": "Some description",
"author": "Lukas",
"main": "dist/index.js",
"module": "dist/index.js",
"files": [ "dist", "README.md" ],
"dependencies": {
.
.
},
"scripts": {
"build": "rm -rf dist && NODE_ENV=production babel src--out-dir dist --copy-files",
.
.
.
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.5",
"#babel/preset-env": "^7.18.2"
}
}
Pushed dist folder to the git.
Installed repository to the host project using NPM
npm install https://github.com/my_custom/react_component.git
Import and use the component from installed git repo
import ConnectorFormView from 'my_react_components';
function App() {
return (
<ConnectorFormView />
);
}
export default App;
Actually that's all. I very recommend to see the attached paper at the beginning of this answer because I maybe skipped very important info for you.

Uncaught Error: Cannot find module 'react-dom/client'

I just create my application from npm command, when i run the start script the application throws me that error.
Please provide more context. If you're using typescript on your react project. You need to upgrade both react and react-dom declaration. npm install #types/react#latest and npm install #types/react-dom#latest
If you've recently updated past npm 8.5+ and using workspaces, you have two options.
Option A) If possible, just remove your package.json declaring your "workspaces" (and the package-lock.json). I had only 1 workspace so that was the easiest fix.
Option B) Update Jest so it can find your modules. I've observed NPM 8.11 will create a node_modules in the workspaces folder and in each project.
Specifically look at the moduleDirectories key below.
{
verbose: true,
testEnvironment: "jsdom",
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: [
// Look in current directory node_modules
path.resolve(__dirname, "node_modules"),
// Look in parent workspace node_modules
path.resolve(__dirname, "../node_modules"),
],
moduleNameMapper: {
...moduleNameMapper,
"\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
'\\.svg$': '<rootDir>/__mocks__/svgrMock.tsx',
"\\.(css)$": "identity-obj-proxy"
},
transform: {
"^.+\\.tsx?$": "ts-jest"
},
};

Babel 7 - Uncaught ReferenceError: regeneratorRuntime is not defined

I'm getting the error Uncaught ReferenceError: regeneratorRuntime is not defined using React with webpack and Babel .
I've followed this answer by defining my .babel.rc as:
{
"presets": ["#babel/preset-env", "#babel/preset-react"] ,
"plugins": [
["#babel/plugin-transform-runtime"]
]
}
and running:
npm i --save-dev #babel/plugin-transform-runtime
However, I get the exact same error afterwards. I've also followed this other answer and this one, but still get the exact same error.
My babel specific installations in package.json are as follows:
"dependencies": {
"#babel/runtime": "^7.14.6"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/plugin-transform-runtime": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5"
}
Any ideas?
hey I ran into the same problem and I am using Babel 7, for me I installed these two dependencies:
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
and this solved my problem
{ "presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "9.2.1"
}
}
],
"#babel/preset-react" ] }
This is my file .babelrc
Look:
#babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
your problemes:
You are using "# babel / preset-env" you must specify the version of node to compile. "node> 7.6". I recommend 10.
Why node > 7.6 Node.js 7.6 has shipped with official support for async/await enabled by default and better performance on low-memory devices.
How do you specify the version: It's simple
targets.node
string | "current".
If you want to compile against the current node version, you can specify "node": "current", which would be the same as "node": process.versions.node.
AND FOR ME LOOK LIKE THIS:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "9.2.1"
}
}
],
"#babel/preset-react"
]
}
This allows the compiler to understand ASYNC AWAIT, hope it helps you!
You can also add a plugin to handle your "asyc away"
https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator
ATTENTION - > This Config is for node-js; it is just a example
This ended up working for me:
How to allow async functions in React + Babel?
My problem was that I was defining the babel plugin in both my .babel.rc file and my webpack.config.js file. I needed to remove that plugin from my webpack.config.js and simply use it only in my .babel.rc file. Then it worked well.

Detox tests are assigned to Undefined, and all e2e are skipped

I installed jest and detox on a fresh react-native init project.
Install jest and jest-circus as per detox docs
Setup iOS build and test configuration
Get the following error consistently on new builds
my .detoxrc.json file:
{
"testRunner": "jest",
"runnerConfig": "e2e/config.json",
"configurations": {
"ios": {
"type": "ios.simulator",
"build": "xcodebuild -workspace ios/rndetox.xcworkspace -scheme rndetox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
"binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/rndetox.app",
"device": {
"type": "iPhone 11"
}
},
"android": {
"type": "android.emulator",
"binaryPath": "SPECIFY_PATH_TO_YOUR_APP_BINARY",
"device": {
"avdName": "Pixel_2_API_29"
}
}
}
}
detox config.json
{
"testEnvironment": "./environment",
"testRunner": "jest-circus/runner",
"testTimeout": 120000,
"testRegex": "\\.e2e\\.js$",
"reporters": ["detox/runners/jest/streamlineReporter"],
"verbose": true
}
and e2e/environment.js
const {
DetoxCircusEnvironment,
SpecReporter,
WorkerAssignReporter,
} = require('detox/runners/jest-circus');
class CustomDetoxEnvironment extends DetoxCircusEnvironment {
constructor(config) {
super(config);
// Can be safely removed, if you are content with the default value (=300000ms)
this.initTimeout = 300000;
// This takes care of generating status logs on a per-spec basis. By default, Jest only reports at file-level.
// This is strictly optional.
this.registerListeners({
SpecReporter,
WorkerAssignReporter,
});
}
}
module.exports = CustomDetoxEnvironment;
I have tried including an init.js with a detox.init but same error.
At the time I tried this, detox was not supported yet on the fresh 0.63 release of React Native. If you build a new project at 0.62 it should be fine. I am not sure if this has been fixed yet though!

Transpiling NextJS for IE 10/11; 'Weakset undefined'

I have a NextJS website I'm building and it's great, except that it does not work in IE 10/11 because some code is not being transpiled correctly. I'm really bad with babel and webpack, and have never had to config them myself before. I've been trying to solve by reading online for two days now, and nothing seems to work for me.
The exact error I get is weakSet is not defined, and it is coming from the common.js file.
Here is my .babelrc file, located in the root of my project.
// .babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", {
"ssr": true,
"displayName": true,
"preprocess": false
}]
]
}
my package.json
{
"name": "bradshouse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next",
"build": "next build",
"start": "next start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^7.0.2",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"react-pose": "^4.0.1",
"styled-components": "^4.0.2"
},
"devDependencies": {
"babel-plugin-styled-components": "^1.8.0"
}
}
The full repo is here if you're interested in launching it yourself. node modules are excluded, so npm install, then npm run build, then npm run start.
https://github.com/TJBlackman/Brads-House
Thanks for the help! Feel free to just link articles and I'll read them thoroughly! Thanks.
Edit: As a quick fix, I added this polyfill script to the <head> of all my pages, and it still did not fix this issue... Wat?! <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
How to support IE 11 by transpiling node_modules code in NextJS
Original answer found in the ziet/nextjs issues thread (view here). Shout out to joaovieira <3
npm install --save-dev babel-polyfill
create a polyfill.js where ever you want it, and inside that file, import the babel-polyfill like so:
import 'babel-polyfill';
Next, if you do not have a next.config.js file, create it at your root directory. Now update your this file to include the following webpack config. Notice how it's using the polyfill file you just made. Full file example:
module.exports = {
webpack: (config) => {
// Unshift polyfills in main entrypoint.
const originalEntry = config.entry;
config.entry = async () => {
const entries = await originalEntry();
if (entries['main.js']) {
entries['main.js'].unshift('./path_to/polyfills.js'); // <- polyfill here
}
return entries;
};
return config;
}
}
Finally, if you don't have a .babelrc file in your project's root directory, create one. Inside it, use the code below that matches the version of babel you're using.
Babel 7
{
"presets": [
[
"next/babel",
{
"preset-env": {
"useBuiltIns": "usage"
}
}
]
]
}
Babel 6
{
"presets": [
[
"next/babel",
{
"preset-env": {
"targets": {
"browsers": "defaults"
},
"useBuiltIns": true
}
}
]
]
}
That's all I know. I'm not even thinking about IE 10...
Good luck!!
I am using next#9.3 with reflect-metadata, and here is my solution:
/** next.config.js > webpack **/
const pathToPolyfills = './src/polyfills.js'
// Fix [TypeError: Reflect.metadata is not a function] during production build
// Thanks to https://leerob.io/blog/things-ive-learned-building-nextjs-apps#polyfills
// There is an official example as well: https://git.io/JfqUF
const originalEntry = config.entry
config.entry = async () => {
const entries = await originalEntry()
Object.keys(entries).forEach(pageBundleEntryJs => {
let sourceFilesIncluded = entries[pageBundleEntryJs]
if (!Array.isArray(sourceFilesIncluded)) {
sourceFilesIncluded = entries[pageBundleEntryJs] = [sourceFilesIncluded]
}
if (!sourceFilesIncluded.some(file => file.includes('polyfills'))) {
sourceFilesIncluded.unshift(pathToPolyfills)
}
})
return entries
}
/** src/polyfills.js **/
// Other polyfills ...
import 'reflect-metadata'

Resources