For a new project i am using Lerna and React Storybook. I want to create a monorepo with multiple packages.
My folder structure looks like this:
.babelrc
.storybook
package.json
node_modules
packages/
button/
.babelrc
node_modules/
package.json
index.js
theme/
node_modules/
package.json
index.js
I want to import the theme from the theme package inside my button package, which i install through npm in my button package.
In my button package i am importing the theme
import theme from '#company/company-theme';
and i get the following error:
Module not found: Error: Can't resolve '#company/company-theme' in buttonpath
At first i thought it was a babel problem and in the package.json i installed the following babel packages
"babel-cli": "^6.26.0",
"babel-jest": "^23.4.2",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"
And in the projectroot and the button root i created a .babelrc and added the following code:
{
"presets": ["env", "react"],
"env": {
"dev": {
"plugins": [
"transform-es2015-modules-commonjs"
]
}
}
}
The problem however still exists. Anyone here knows what to do?
Related
I have created a monorepo using yarn#3 workspaces.
My root package.json:
{
"name": "hello-yarn-workspaces",
"packageManager": "yarn#3.1.1",
"workspaces": [
"apps/*",
"packages/*"
],
"devDependencies": {
"#commitlint/cli": "^16.0.1",
"#commitlint/config-conventional": "^16.0.0",
"husky": "^7.0.4"
},
"scripts": {
"postinstall": "husky install",
"prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
}
}
The package.json in apps/ui:
{
"name": "ui",
"packageManager": "yarn#3.1.1",
"scripts": {
"dev": "vite"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#tailwindcss/forms": "^0.4.0",
"#types/react": "^17.0.38",
"#types/react-dom": "^17.0.11",
"#vitejs/plugin-react": "^1.1.3",
"autoprefixer": "latest",
"postcss": "latest",
"tailwindcss": "latest",
"typescript": "^4.5.4",
"vite": "^2.7.10"
}
}
I have created a component inside my apps/ui/src folder and when I run yarn workspace ui run dev, the app can be started in the browser.
However, when opening my monorepo in VS Code, it fails to resolve npm packages in import statements:
// Cannot find module 'react' or its corresponding type declarations.ts(2307)
import React, { ReactElement, useState } from 'react'
The same happens for the vite.config.ts in apps/ui
// Cannot find module 'vite' or its corresponding type declarations.ts(2307)
import { defineConfig } from 'vite'
// Cannot find module '#vitejs/plugin-react' or its corresponding type declarations.ts(2307)
import react from '#vitejs/plugin-react'
When opening the monorepo in WebStorm, everything is ok.
The repro repository can be found here.
Update: It looks like it is related to the PnP mechanism. I came across this question and setting nodeLinker: node-modules in .yarnrc.yml followed by yarn install fixed it.
However, the ansers for this question didn't work for me.
I get this error in VS Code after running yarn dlx #yarnpkg/sdks vscode:
The path /Users/alexzeitler/src/hello-yarn-workspaces/.yarn/sdks/typescript/lib/tsserver.js doesn't point to a valid tsserver install. Falling back to bundled TypeScript version.
The files in .yarn/sdks/typescript/lib actually don't exist but I have a file integrations.yml in .yarn/sdks:
# This file is automatically generated by #yarnpkg/sdks.
# Manual changes might be lost!
integrations:
- vscode
Looks like the missing pieces have been due to the PnP configuration:
yarn add --dev typescript ts-node prettier
yarn dlx #yarnpkg/sdks vscode
Add a minimal tsconfig.json:
{
"compilerOptions": {
/* Basic Options */
"target": "es5",
"module": "commonjs",
"lib": ["ESNext"],
/* Strict Type-Checking Options */
"strict": true,
/* Module Resolution Options */
"moduleResolution": "node",
"esModuleInterop": true,
/* Advanced Options */
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
}
}
Then install this VS Code extension followed by these steps:
Press ctrl+shift+p in a TypeScript file
Choose "Select TypeScript Version"
Pick "Use Workspace Version"
More details can be found in the docs.
I'm experimenting with yarn workspace monorepo. It is consisting of a TestProject created with create-react-app, and a SharedLib1 which is created with create-react-library. TestProject imports code from SharedLib1. The problem being, TestProject uses react-scripts 3.3.0 which is dependent on babel-jest ^24.9.0, while SharedLib1 uses react-scripts-ts ^2.16.0 which is dependent on babel-jest 22.4.4. When running yarn start in TestProject, it complains:
The react-scripts package provided by Create React App requires a dependency:
"babel-jest": "^24.9.0"
Don't try to install it manually: your package manager does it automatically.
However, a different version of babel-jest was detected higher up in the tree:
/monoRepo/node_modules/babel-jest (version: 22.4.4)
I could disable the error by setting SKIP_PREFLIGHT_CHECK=true in TestProject or manually upgrade the react-scripts inside SharedLib1, but I'd like to know if there's a better way of handling this.
myMonorepo
-web
-SharedLib1
-package.json
-TestProject
-package.json
-package.json
Package.json of myMonoRepo:
{
"name": "my-mono-repo",
"version": "0.1.0",
"private": true,
"workspaces": [
"web/*"
],
"nohoist": [
"**/babel-jest",
"**/babel-jest/**"
]
}
Package.json of myMonoRepo:
{
"name": "test-proj",
"version": "0.1.0",
"private": true,
"dependencies": {
...
"shared-lib-1": "^1.0.0"
}
}
And the test code App.tsx:
import React from 'react';
import TestComp from 'shared-lib-1';
import './App.css';
const App: React.FC = () => {
return (
<div className="App">
<TestComp text={'aaa'}/>
Learn React
</div>
);
}
export default App;
There is a babel-jest 24.9.0 inside the node_modules of TestProj and another 22.4.4 inside the node_modules of myMonoRepo
This is very similar, if not the same, to an issue opened on the GH repo for create-react-app and you may find additional information there.
That said, you might try moving babel-jest to a devDependency instead of a package dependency. If that does not work, you might try Selective dependency resolutions, where you can force your project to a specific version of babel-jest -
"resolutions": {
"babel-jest": "^24.9.0",
"shared-lib-1": "^1.0.0"
}
I am trying to use React with Symfony 4 but i couldn't achieve.
When i try to build webpack i got the following error for every .js file that i added to webpack.config.js via .addEntry()
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
at assertNoDuplicates (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-descriptors.js:205:13)
at createDescriptors (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-descriptors.js:114:3)
at createPresetDescriptors (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-descriptors.js:101:10)
at passPerPreset (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-descriptors.js:58:96)
at cachedFunction (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/caching.js:33:19)
at presets.presets (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-descriptors.js:29:84)
at mergeChainOpts (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-chain.js:320:26)
at /var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-chain.js:283:7
at buildRootChain (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/config-chain.js:68:29)
at loadPrivatePartialConfig (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/partial.js:85:55)
at Object.loadPartialConfig (/var/www/admin.whenandwhere.events/node_modules/#babel/core/lib/config/partial.js:110:18)
at Object.<anonymous> (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:140:26)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:3:103)
at _next (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:5:194)
at /var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:5:364
at new Promise (<anonymous>)
at Object.<anonymous> (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:5:97)
at Object._loader (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:220:18)
at Object.loader (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:56:18)
at Object.<anonymous> (/var/www/admin.whenandwhere.events/node_modules/babel-loader/lib/index.js:51:12)
But i didn't specify any plugin neither .babelrc or webpack.config.js.
Here are my files
webpack.config.js
var Encore = require('#symfony/webpack-encore');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.addEntry('app', './assets/js/main.js')
.addStyleEntry('global', './assets/css/global.scss')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableSassLoader()
.autoProvidejQuery()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.enableReactPreset()
.configureBabel((config) => {
config.presets.push(
['#babel/env'],
['#babel/react'],
)})
.addEntry('react', './assets/js/reactGeoSuggest.js')
;
module.exports = Encore.getWebpackConfig();
package.json
{
"devDependencies": {
"#babel/preset-react": "^7.0.0",
"#symfony/webpack-encore": "^0.23.0",
"bootstrap": "^4.3.1",
"bootstrap-sass": "^3.4.1",
"jquery": "^3.3.1",
"node-sass": "^4.11.0",
"popper.js": "^1.14.7",
"sass-loader": "^7.1.0",
"webpack-notifier": "^1.6.0"
},
"dependencies": {
"#babel/preset-env": "^7.3.4",
"babel-loader": "^8.0.5",
"prop-types": "^15.7.2",
"react": "^16.8.4",
"react-dom": "^16.8.4"
}
}
I don't have any .babelrc file.
So it looks very strange for me getting this error, i tried to follow a few tutorials but they were outdated due to babel 7 changes. Now i am stuck at this error.
Remove .enableReactPreset() or config.presets.push(['#babel/env'], ['#babel/react'])})
These basicly do the same thing, if no .babelrc file is present.
First of all, your configuration is conflicted each other. As long as, you would like to use Encore and Symfony with React, you're supposed to watch this tutorial.
https://symfonycasts.com/screencast/webpack-encore
In addition, If you prefer to go ahead with this, you should run this command add that file.
npm install -D #babel/core #babel/preset-env babel-loader
.babelrc
{
"presets": ["#babel/preset-env"]
}
I had a similar issue when I try to run a react project. I have fixed the issue by modifying the package.json file.
Simple solution: just delete the "^" in "#babel/preset-react": "^7.0.0", from your package.json file, And run the npm install command after npm cache verify.
Your webpack.config.js contains babel/env. But there is not any package with same name in npm repository. There is babel-preset-env. This package webpack encore includes by default - according to Symfony documentation "Configuring Babel"
https://symfony.com/doc/current/frontend/encore/babel.html
Babel is automatically configured for all .js and .jsx files via the
babel-loader with sensible defaults (e.g. with the #babel/preset-env
and #babel/preset-react if requested).
So try change your config to this:
.enableReactPreset()
.configureBabel(function(babelConfig) {
}, {
});
You don't need add '#babel/react' as preset in webpack config
because option .enableReactPreset() already has been doing this https://github.com/symfony/webpack-encore/blob/v0.27.0/lib/loaders/babel.js#L57-L61
If you need enable additional presets or plugins use this syntax according Symfony Documentation "Configuring Babel"
Also your package.json is redundant. You can remove from its:
#babel/preset-react
#babel/preset-env
babel-loader
redundant
These packages has been already included as dependency for #symfony/webpack-encore
See here https://github.com/symfony/webpack-encore/blob/v0.27.0/package.json
im using React in Symfony, installed Jest and Enzyme to test the React components, but when trying to run tests with yarn test or even yarn test --no-cache got following error:
here is my package.json file:
{
"devDependencies": {
"#symfony/webpack-encore": "^0.20.1",
"babel-jest": "^23.2.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.4",
"jest": "^23.2.0",
"jest-enzyme": "^6.0.2",
"webpack-notifier": "^1.6.0"
},
"dependencies": {
"axios": "^0.18.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"moment": "^2.22.2",
"prop-types": "^15.6.2",
"rc-datetime-picker": "^1.6.1",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0"
},
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
},
"jest": {
"transform": {
"^.+\\.js$": "babel-jest"
},
"setupTestFrameworkScriptFile": "./assets/js/__tests__/setup/setupEnzyme.js",
"testPathIgnorePatterns": [
"./assets/js/__tests__/setup/"
]
}
}
and my webpack.config.js(encore) file:
var Encore = require('#symfony/webpack-encore');
Encore
// the project directory where all compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/build')
// will create public/build/app.js and public/build/app.css
.addEntry('app', './assets/js/index.js')
// allow legacy applications to use $/jQuery as a global variable
.autoProvidejQuery()
// enable source maps during development
.enableSourceMaps(!Encore.isProduction())
// empty the outputPath dir before each build
.cleanupOutputBeforeBuild()
// show OS notifications when builds finish/fail
.enableBuildNotifications()
.enableReactPreset()
// first, install any presets you want to use (e.g. yarn add babel-preset-es2017)
// then, modify the default Babel configuration
.configureBabel(function(babelConfig) {
// add additional plugins
babelConfig.plugins.push('transform-object-rest-spread');
// no plugins are added by default, but you can add some
// babelConfig.plugins.push('styled-jsx/babel');
})
// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()
// allow sass/scss files to be processed
// .enableSassLoader()
;
// export the final configuration
module.exports = Encore.getWebpackConfig();
and finally my setupEnzyme.js:
const Enzyme = require('enzyme');
// this is where we reference the adapter package we installed
// earlier
const EnzymeAdapter = require('enzyme-adapter-react-16');
// This sets up the adapter to be used by Enzyme
Enzyme.configure({ adapter: new EnzymeAdapter() });
I tried all of the available solutions but none of them worked for me!
any idea about it? :(
I know that this reply comes about 2 years after the post was created, however I have faced similar problem with Jest/Enzyme tests under React/Symfony 5/Encore setup. Here is a valid solution for the issue:
Comment Babel configuration from webpack.config.js (used by Encore) and create custom configuration with regular babel.config.js file:
webpag.config.js - comment Encore configureBabelPresetEnv babel setup:
/*
* Commented as babel.config.js is used
* The "callback" argument of configureBabelPresetEnv()
* will not be used because your app already provides an
* external Babel configuration (e.g. a ".babelrc" or "babel.config.js"
* file or "babel" key in "package.json").
*/
//enables #babel/preset-env polyfills
//.configureBabelPresetEnv((config) => {
// config.useBuiltIns = 'usage';
// config.corejs = 3;
//})
babel.config.js - create this configuration file at the root of your project. It will serve Jest to grab babel preset and overload part of Encore configuration (commented previously in webpack.config.js):
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
browsers: [
"> 0.5%",
"last 2 versions",
"IE 11"
]
},
useBuiltIns: 'usage',
corejs : {
version: "3",
proposals : true
}
},
],
['#babel/preset-react'],
['#babel/preset-typescript']
],
plugins: ["#babel/plugin-syntax-jsx"]
};
Setup Jest using following files:
setup.js - create the file in your test directory
import React from 'react';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
finally update jest.config.js file with lines below:
module.exports = {
rootDir: './assets',
//test files
testRegex: './assets/js/.*test\\.js$',
//setup
setupFiles: ['<rootDir>/tests/setup.js'],
//alias list to integrate swiftly nested directories
//this can be skipped if not needed
moduleNameMapper: {
'^#constants(.*)$': '<rootDir>/js/constants',
'^#containers(.*)$': '<rootDir>/js/containers',
'^#store(.*)$': '<rootDir>/js/store',
//identity-obj-proxy to integrate styles/images etc.
//this can be skipped if not needed
'\\.(css|less|scss|jpg|jpeg|png)$': 'identity-obj-proxy'
}
};
List of dependencies I have used to make Jest/Enzyme working with React/Symfony 5:
npm install --save-dev jest
npm install --save-dev enzyme
npm install --save-dev enzyme-adapter-react-16
npm install --save-dev #babel/plugin-syntax-jsx
npm install --save-dev #babel/preset-typescript
npm install --save-dev identity-obj-proxy
Final implementation can be found here:
symfony-react-jest-enzyme
Voila, hope this will help someone.
I'm attempting to use React Storybook in a project that already has an extensive Webpack 2 config. I started the Storybook following the basic steps:
npm i -g #storybook/cli
getstorybook
When I run yarn storybook, it breaks on the JSX of the demo component:
ERROR in ./stories/index.jsx
Module parse failed: /Users/alexanderhadik/project/web/node_modules/#storybook/react/node_modules/babel-loader/lib/index.js??ref--0!/Users/alexanderhadik/project/web/stories/index.jsx Unexpected token (9:55)
You may need an appropriate loader to handle this file type.
| import { Button, Welcome } from '#storybook/react/demo';
|
| storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);
|
| storiesOf('Button', module)
# ./.storybook/config.js 4:2-23
# multi ./node_modules/#storybook/react/dist/server/config/polyfills.js ./node_modules/#storybook/react/dist/server/config/globals.js ./node_modules/webpack-hot-middleware/client.js?reload=true ./.storybook/config.js
Since I didn't start this project originally using create-react-app - do I need to modify the Storybook webpack config to enable JSX?
This might to be a problem with Storybook not replicating webpack babelrc behaviour exactly.
In my case, I had an empty (just {}) .babelrc file with all the important react/jsx plugins defined in webpack.config.js. Storybook read the .babelrc instead of using the babel settings in webpack.config.js.
Deleting the .babelrc solved that issue.
in my case, i didnt have a .babelrc at all -- i used the entry "babel" in the package.json. when running the storybook in this project, the babel entry wasnt there. i added it and things magically started working.
{
"name": "root",
"private": true,
"devDependencies": {
"#storybook/addon-actions": "^4.1.11",
"#storybook/addon-links": "^4.1.11",
"#storybook/addons": "^4.1.11",
"#storybook/react": "^4.1.11",
...
},
"dependencies": {},
"scripts": {
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook"
},
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
}
i hope this helps someone.