Unable to load a react module as node module - javascript

I have a react component in the path
src/components/test
import React from 'react';
import ReactDom from 'react-dom';
class TestComp extends React.Component {}
export default TestComp;
I am exposing the component in index.js from path
src/index.js
import TestComp from './components/test';
export {
TestComp
};
I have added main in package.json as "main": "src/index.js"
I have published a npm package test-comp of above application and using same in another application.
main.js
import {TestComp} from 'test-comp';
I am using grunt-browserify in this application with following options set.
options: {
"transform": [
[
"babelify",
{
"presets": [
"es2015",
"react",
"stage-0"
]
}
]
],
browserifyOptions: {
debug: true,
extensions: ['.js', '.jsx'],
entries: ['main.js']
}
}
When I run grunt browserify getting following error.
>> import TestComp from './components/test';
>> ^
>> ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Warning: Error running grunt-browserify. Use --force to continue.
It probably not understanding the path mentioned in node module or rejecting to understand the same which linting. I even have tried adding following in .eslintrc but no luck
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"browser": true,
"es6": true
},
"ecmaFeatures": {
"modules": true
}
}
I tried most of SO answers related to this error. But still stuck in same place.
EDIT
I am able to browserify first module directly with almost similar configuration. Getting this error when first module is loaded as node dependancy in other application as explained above.

So you wrote the module test-comp in ES6, using import and export, and the main entry of the package.json in test-comp refers to src/index.js.
The answer is that browserify transforms don't apply to every module you require. They only apply to the immediate project: not the project's dependencies.
If you want to require a module that uses ES6 syntax in browserify, you'll either need to
Add a prepublish script to test-comp that transpiles it to ES5, and change the main entry of test-comp to refer to that ES5 version, not the ES6 version
Add babelify as a dependency of test-comp and add babelify as a browserify transform in the package's 'browserify' entry, as documented in babelify.

Related

Vite Js --> dev mode works, but build doesn't. (importing library causes error)

I tried to move from vue-cli to vite but observed some obstacles.
I want to include several npm packages into my vue 3 project.
I tried to understand the issue, and basically the error came when I imported
https://www.npmjs.com/package/rdf-parse
If I run npm run dev everything works as expected, but when I run npm run build and serve the dist folder with http-server the error:
Uncaught TypeError: Object.defineProperty called on non-object at Function.defineProperty
occurs.
The code worked with vue-cli and in vite-dev mode so I expect I missed somethin crucial in the vite.config.js
But I didnt find anything in the docu that helped me out and also no thread here on stackoverflow or elsewhere.
I created a repo with a minimal example here: https://github.com/stackoverflowuser/vite-issue
It is the npm vue3 template (npm init vue#3) and only the library rdf-parse is added.
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url)),
}
},
build: {
target: "es2020"
},
optimizeDeps: {
esbuildOptions: {
// Limit target browsers due to issue: Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari13" + 2 overrides)'
target: "es2020",
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeModulesPolyfillPlugin()
]
}
},
})
In hope someone can give me a hint.

Jest fails when rendering React component with 'No element indexed by'

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:
When I run any test that renders a component, it spits out the error No element indexed by 7.
Here is the full stack trace:
FAIL __tests__/App-test.tsx
● Test suite failed to run
No element indexed by 7
at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
at Function.write (node_modules/#jest/console/build/BufferedConsole.js:101:7)
at console._log (node_modules/#jest/console/build/BufferedConsole.js:117:21)
at console.error (node_modules/#jest/console/build/BufferedConsole.js:161:10)
This same error occurs with any component I attempt to render.
Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest #babel/core #babel/preset-env) and setting "coverageProvider" in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It's definitely possible that I configured something else wrong. Here are some code snippets which may be of use:
App-test.tsx
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
package.json
// ...
"jest": {
"preset": "react-native",
"coverageProvider": "babel",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|#react-native|react-native-video|react-native-reanimated|#miblanchard/react-native-slider|react-native-gesture-handler)/)"
],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-typescript', {allowDeclareFields: true}],
],
plugins: [
"react-native-reanimated/plugin",
],
};
As an additional note, I have tried adding #babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.
Edited to note that these tests fail regardless of whether or not the --coverage argument is applied
In the end, I solved my error by uninstalling node_modules, re-running npm install --save-dev babel-jest #babel/core #babel/preset-env and adding
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js",
// ...
]
to my package.json

SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial

I can't get vue testing to work with vue-test-utils and jest. I created a clean new project with vue cli and added jest as follows, maybe someone can follow along and tell me what I'm doing wrong. (I'm following this installation guide: https://vue-test-utils.vuejs.org/installation/#semantic-versioning)
vue create jest-test
1.1. npm install
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
Created example.test.js in a tests directory under the project root (jest-test/tests)
Added the following to this file:
import { mount } from '#vue/test-utils'
import HelloWorld from "#/components/HelloWorld";
test('displays message', () => {
const wrapper = mount(HelloWorld)
expect(wrapper.text()).toContain('Welcome to Your Vue.js App')
})
Added the following to the package.json scripts:
"jest": "jest"
npm run jest
Get the following error:
C:\Users\xxx\jest-test\tests\example.test.js:1
import { mount } from '#vue/test-utils'
^^^^^^
SyntaxError: Cannot use import statement outside a module
Same happens with Mocha or if I try it in an existing project. Is this a bug? I can't get it working, no matter what I do.
Edit: If I do it with Vue CLI, it works
https://vue-test-utils.vuejs.org/installation/#installation-with-vue-cli-recommended
You need to transform both *.vue files and *.js files.
I tried your setup and could reproduce the issue. But after altering jest.config.js to the following, the tests will run fine:
module.exports = {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
transform: {
'.*\\.js$':'babel-jest',
".*\\.(vue)$": "vue-jest"
},
moduleNameMapper: {
"#/(.*)": "<rootDir>/src/$1",
},
testEnvironment: 'jsdom'
}

SyntaxError: Cannot use import statement outside a module in Javascript/Jest

I'm trying to run a test in jest. When I add my import:
import { AnimalFactory } from "../../AnimalFactory";
I get the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from "axios/index";
SyntaxError: Cannot use import statement outside a module in Javascript/Jest
I believe something about import axios from axios/index is causing an issue. How can I fix this?
I read some suggestions to include "type": "module", so I've added to package.json as an additional line but nothing seems to change
I'm also getting this error:
Cannot find module 'axios/index' from 'AnimalFactory.js'
However, Jest was able to find:
'../../AnimalFactory.js'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
What i've done:
installed babel and the plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
webpack:
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-modules-commonjs"
]
},

How to set paths properly in react-native

In my React-Native application, import paths are like this.
import {
ScreenContainer,
SLButton,
SLTextInput,
} from '../../../../../components';
import { KeyBoardTypes } from '../../../../../enums';
import { SIGN_UP_FORM } from '../../../../constants/forms';
I have seen some applications, there the paths are more clear and elegant without '../../../'s. How can I achieve this in React-Native??
I saw in my solution that, in every folder there was a package.json file. I'm not sure if that is the proper way to do it.
You need to configure alias in webpack.config.js. You can find an example here and here
webpack.config.js:
alias: {
'#': path.join(__dirname, 'src')
}
your.js.file.js
import '#/utils/classComponentHooks';
if you don't use wepback for react-native (despite you can). You can also try .babelrc
[
'module-resolver',
{
root: ['./src'],
alias: {
'#': './src',
},
},
];
Starting around React Native version 0.55 (I'm not sure exactly when this was enabled) you can just use your project name as the path root.
import {DatePanel} from 'MyProject/components/panels';
import HomeScreen from 'MyProject/screens/HomeScreen';
No problems with flow, Xcode, etc.
It's possible. I've done it, but I don't recommend it. It doesn't work when xcode starts bundler because you have to do npm start -- --reset-cache. You have to use workarounds to learn your IDE understand this paths. It doesn't work with Flow.
You can use npm babel-plugin-module-resolver. Babel is used by metro budler.
.babelrc.
{
"presets": ["react-native"],
"plugins": [
[
"module-resolver",
{
"root": ["./src"],
"alias": {
"src": "./src",
"root": "./"
}
}
]
],
}

Categories