Jest cannot find module in workspace - npm

I have an NPM project structured in workspaces:
proj/
+-node_modules/
+-packages/
+-pkg1/
+-src/
|-c1.ts
|-c1.test.ts
|-package.json
|-jest.config.js
+-pkg2/
+-src/
|-c2.ts
|-package.json
+-apps/
|-package.json
The project's package.json:
{
"name": "proj",
"scripts": {
...
"test:pkg1": "npm test -w packages/pkg1",
},
"workspaces": [
"packages/*",
"apps/*"
]
}
The package.json inside pkg1:
{
"name": "#proj/pkg1",
"scripts": {
...
"test": "jest --config=jest.config.js",
},
"devDependencies": {
"#types/pegjs": "0.10.3",
"#types/jest": "29.1.1",
"ts-loader": "9.3.1",
"typescript": "4.8.3",
"webpack": "5.74.0",
"webpack-cli": "4.10.0",
"jest": "29.1.2",
"ts-jest": "29.0.3"
},
"dependencies": {
"#proj/pkg2": "1.0.0"
}
}
The test file c1.test.ts is:
import { Component1 } from "#proj/pkg2";
describe("some tests", () => {
test("a test case", () => {
// Arrange ...
// Act ...
// Assert ...
});
});
The problem
When, from the project's root, I run: npm run test:pkg1, I get:
> 1 | import { Component1 } from "#proj/pkg2";
| ^
3 | describe("some tests", () => {
4 | test("a test case", () => {
5 | // Arrange
at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:487:11)
Jest cannot find "#proj/pkg2". It makes sense as it cannot understand workspaces and Jest compiles all files before running the tests. How to solve this?

Related

webpack 5 with babel build not exporting functions

I am trying to build and publish a react component to npm. I am using webpack 5 with babel. The build succeeds, but when I try use the component it is aparent that the component is not being exported as I get the following error in the console:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check your code at App.js:41.
at App
My project structure looks like this:
- src/
- components/
- MyComponent.js
- styles/
- MyComponent.css
- index.js
- .babelrc
- package.json
- webpack.config.js
MyComponent.js contains the following:
import '../styles/MyComponent.css'
export default function MyComponentFunction() {
return (
<h1>Hello</h1>
)
}
My index.js file contains the following:
import MyComponentFunction from './components/MyComponent'
export default {
MyComponentFunction
}
My .babelrc file contains the following:
{
"presets": ["#babel/preset-env","#babel/preset-react" ]
}
My webpack.config.js contains the following:
const path = require('path')
module.exports = {
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader:'babel-loader',
},
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
exclude: /node_modules/
}
]
}
}
And my package.json (which includes lots of unused libraries) contains the following:
{
"name": "my-component",
"version": "0.0.1",
"description": "A react component ...",
"main": "dist/index.bundle.js",
"scripts": {
"build": "webpack --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
...
},
"keywords": [
],
"author": "<Author>",
"license": "MIT",
"bugs": {
"url": "<github repo>"
},
"homepage": "<github repo>#readme",
"devDependencies": {
"#babel/core": "^7.19.6",
"#babel/plugin-proposal-export-default-from": "^7.18.10",
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/preset-env": "^7.19.4",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"eslint-webpack-plugin": "^3.2.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
},
"dependencies": {
"#react-three/drei": "^9.36.0",
"#react-three/fiber": "^8.8.10",
"react": "^18.2.0",
"three": "^0.145.0"
},
"peerDependencies": {
"react": "^18.2.0"
}
}
Why can I not import my component after it has been published? Which i'm trying to do like so:
import {MyComponentFunction} from 'my-component'
function App() {
return (
<>
<MyComponentFunction></MyComponentFunction>
</>
);
}
The reason you are facing this issue is that you have named the package as an exact match for this. The name must be unique.

electron ENOENT error when running in gitlab CI pipeline

I'm running a job in gitlab CI and getting the following error when executing testcafe command.
The tests do pass locally.
Error
spawn /builds/testcafe-reporter/node_modules/nightmare/node_modules/electron/dist/electron ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:268:19)
at onErrorNT (internal/child_process.js:470:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Gitlab stage:
- yarn install --frozen-lockfile
- yarn add electron
- yarn testcafe:generatereport
package.json
{
"name": "testcafe-reporter",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"testcafe:generatereport": "yarn testcafe ./testcafeReportGeneratorTest.ts"
},
"dependencies": {
"node-html-parser": "^4.1.4",
"testcafe": "1.16.0",
"testcafe-browser-provider-nightmare": "^0.0.5",
"testcafe-reporter-html": "^1.4.6",
"testcafe-reporter-html-testrail": "^3.1.5",
"typescript": "^4.4.2"
}
}
.testcafec.json
{
"browsers": ["nightmare"],
"reporter": {
"name": "html",
"output": "testcafe/reports/report.html"
}
}
Please advise how can I resolve this?
I cannot reproduce this issue either locally or in Gitlab CI. Here are the files I am trying with:
.testcafec.json
{
"browsers": ["nightmare"],
"reporter": {
"name": "html",
"output": "testcafe/reports/report.html"
}
}
package.json
{
"name": "testcafe-reporter",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"testcafe:generatereport": "yarn testcafe ./testcafeReportGeneratorTest.ts"
},
"dependencies": {
"electron": "^14.0.0",
"nightmare": "^3.0.2",
"node-html-parser": "^4.1.4",
"testcafe": "1.16.0",
"testcafe-browser-provider-nightmare": "^0.0.5",
"testcafe-reporter-html": "^1.4.6",
"testcafe-reporter-html-testrail": "^3.1.5",
"typescript": "^4.4.2",
"vo": "^4.0.2"
}
}
testcafeReportGeneratorTest.ts
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
const developerName = Selector('#developer-name');
test('How to type text into an input (t.typeText user action)', async t => {
await t
.typeText(developerName, 'Peter')
.typeText(developerName, 'Paker', { replace: true })
.typeText(developerName, 'r', { caretPos: 2 })
.expect(developerName.value).eql('Parker');
});
Could you check if this issue is reproducible with these files?

Vite.js build with lib option not loading react app

Below is my current vite config.js/ package.json and tsconfig.json with build with lib configuration, it worked properly using with normal vite build but fails does not work on build lib.
The files are generated in dist folder but app doesn't loads
vite.config.js
`/* eslint-disable import/no-extraneous-dependencies */
import reactRefresh from '#vitejs/plugin-react-refresh';
import path from 'path';
import { Alias, defineConfig } from 'vite';
import * as tsconfig from './tsconfig.paths.json';
function readAliasFromTsConfig(): Alias[] {
const pathReplaceRegex = new RegExp(/\/\*$/, '');
return Object.entries(tsconfig.compilerOptions.paths).reduce(
(aliases, [fromPaths, toPaths]) => {
const find = fromPaths.replace(pathReplaceRegex, '');
const toPath = toPaths[0].replace(pathReplaceRegex, '');
const replacement = path.resolve(__dirname, toPath);
aliases.push({ find, replacement });
return aliases;
},
[] as Alias[],
);
}
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, "src/main.tsx"),
name: "Aagam",
},
rollupOptions: {
external: ["react"],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
react: 'React',
},
},
},
minify: true,
sourcemap: false,
},
plugins: [reactRefresh()],
resolve: {
alias: readAliasFromTsConfig(),
},
css: {
modules: { localsConvention: 'camelCase' },
preprocessorOptions: {
scss: {
additionalData: `$injectedColor: orange;`
}
}
}
});
> `
package.json
"name": "reporting-ui-component",
"version": "1.0.0",
"files": [
"dist"
],
"typings": "./dist/reporting-ui-component.d.ts",
"main": "./dist/reporting-ui-component.umd.js",
"module": "./dist/reporting-ui-component.es.js",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && tsc -P tsconfig.dts.json",
"serve": "vite preview",
"start": "npm run dev",
"lint:fix": "eslint src --ext .jsx,.js,.ts,.tsx --quiet --fix",
"lint:format": "prettier --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\" ",
"lint": "yarn lint:format && yarn lint:fix ",
"type-check": "tsc",
"lint-staged": "npx lint-staged -r",
"validate": "npm run style",
"validate-commit": "npm run lint-staged",
"style": "npx -q eslint src --ext .ts,.tsx --fix"
}
tsconfig.dts.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"declarationDir": "dist",
"emitDeclarationOnly": true
},
"include": ["src"]
}
It would be great if you could provide some solution to it?
I am getting error on running above config
In order to make sure your project is rendered from the output generated by lib, make sure to refer the start point of your app i.e. index.html to have the below script
<script src="/dist/<your-file-name>.umd.js"></script>
in place of previous path
<script type="module" src="/src/main.tsx"></script>
and it should start working

How to set up Tailwind responsive variants for production build?

I set up responsive variants in my create-react-app app after setting up Craco according to Tailwind Docs. These work perfectly in development build but no images load in production build. What am I missing here?
I have determined the issue is most likely in my production configuration. When I "hard-code" any of the background-image URLs directly into my App.css file as a test, they show up correctly in production build.
index.css
#tailwind base;
#tailwind components;
#tailwind utilities;
#layer utilities {
#variants responsive {
.test-XS {
background-image: url('https://res.cloudinary.com/.../test-XS.png');
}
.test-SM {
background-image: url('https://res.cloudinary.com/.../test-SM.png');
}
.test-MD {
background-image: url('https://res.cloudinary.com/.../test-MD.png');
}
.test-LG {
background-image: url('https://res.cloudinary.com/.../test-LG.png');
}
.test-XL {
background-image: url('https://res.cloudinary.com/.../test-XL.png');
}
}
/* There are about 20 more sets of these for different images */
}
package.json :
{
"homepage": "http://xxx.github.io/yyy",
"name": "color-portfolio",
"version": "0.1.0",
"private": true,
"dependencies": {
"#craco/craco": "^6.1.1",
"#tailwindcss/postcss7-compat": "^2.0.2",
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.5",
"#testing-library/user-event": "^12.6.3",
"autoprefixer": "^9.8.6",
"postcss": "^7.0.35",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.2",
"tailwindcss": "npm:#tailwindcss/postcss7-compat#^2.0.2",
"web-vitals": "^1.1.0"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"gh-pages": "^3.1.0"
}
}
craco.config.js :
module.exports = {
style: {
postcss: {
plugins: [
require('tailwindcss'),
require('autoprefixer'),
],
},
},
}
tailwind.config.js :
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx,css}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
The issue was in the concatenation I was using in my classNames.
It is covered in Tailwind's documentation here.
"Don't use string concatenation to create class names"
An example of what I was doing incorrectly:
<div className={`card bg-contain ${props.image}-XS sm:${props.image}-SM md:${props.image}-MD lg:${props.image}-LG xl:${props.image}-XL`}>
My workaround to get my project deployed for now: Changing it so that Tailwind does not "tree-shake" the utilities layer by specifying which layers to purge in config (more info in Tailwind Docs here):
tailwind.config.js :
module.exports = {
purge: {
layers: ['base', 'components'],
content: ['./src/**/*.{js,ts,tsx}', './public/index.html']
},
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
I am sure that this makes my build size unnecessarily large, but at least my project is deployed until I figured out a better way to incorporate these dynamic class variants.

Trying to get a simple webpack build using tailwind, getting unknown word error

I'm trying to get tailwindcss to work with webpack.
Currently I am getting the following error when running npx webpack:
ERROR in ./src/index.js
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError
(2:3) Unknown word
1 | function hello(){
> 2 | console.log('hi');
| ^
3 | }
4 |
package.json
{
"name": "blank",
"version": "1.0.0",
"license": "MIT",
"private": true,
"scripts": {
"test": "echo \" no tests specified yo \" && exit 1",
"build": "webpack"
},
"dependencies": {
"tailwindcss": "^1.4.6"
},
"devDependencies": {
"css-loader": "^3.5.3",
"postcss": "^7.0.32",
"postcss-loader": "^3.0.0",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
// ...
use: [
// ...
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('tailwindcss'),
require('autoprefixer'),
],
},
},
],
}],
}
}
tailwind.config.js
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
src/index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<script src="main.js"></script>
<p>hello</p>
</body>
</html>
src/index.js
function hello(){
console.log('hi');
}
src/styles.css
/* src/styles.css */
#tailwind base;
#tailwind components;
#tailwind utilities;
Also, how can I reference the styles.css in my index.html file? Do I have to grab it from the /dist folder once it is built?