Twin Macro can't get daisyui (tailwind's plugin) class on NX workspace project - reactjs

I'm creating project with nx, and also use nx preset to setup the project,and I tried to add some ready-to-go UI lib, adding tailwind first, then adding 'daisyui' the tailwind components. But I got the issue that seems macro can't find daisyui class. for normal tailwind class it's working properly.
if you need more context and file config that I'm missing to show here, please tell me. thankyou for all your helps.
Error:
ERROR in ./src/app/app.tsx
Module build failed (from ../../node_modules/#nrwl/web/src/utils/web-babel-loader.js):
MacroError: path/on/my/machine/mono-repo/apps/appname/src/app/app.tsx:
✕ btn was not found
btn is button className on daisyui component.
How I use twin macro
import styled from "#emotion/styled"
import tw from "twin.macro"
...
const StyledButton = styled.button`
${tw`btn btn-primary`}
`
.babelrc
{
"presets": [
[
"#nrwl/react/babel",
{
"runtime": "automatic",
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
],
"#emotion/babel-preset-css-prop",
"#babel/preset-typescript"
],
"plugins": [
"babel-plugin-transform-inline-environment-variables",
["babel-plugin-twin", { "debug": true }],
"babel-plugin-macros",
[
"#emotion/babel-plugin-jsx-pragmatic",
{
"export": "jsx",
"import": "__cssprop",
"module": "#emotion/react"
}
],
[
"#babel/plugin-transform-react-jsx",
{
"pragma": "__cssprop",
"pragmaFrag": "React.Fragment"
}
]
]
}
and project.json setup config
{
"root": "apps/appname",
"sourceRoot": "apps/appname/src",
"projectType": "application",
"targets": {
"build": {
"executor": "#nrwl/web:webpack",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"compiler": "babel",
....others config ....
"styles": ["apps/sandbox/src/styles.scss"],
"scripts": [],
"webpackConfig": "apps/sandbox/webpackConfig.js"
},
...
}
...
}
my webpackConfig.js
const webpack = require("webpack")
const nrwlConfig = require("#nrwl/react/plugins/webpack.js")
const webpackTailwindConfig = require("./webpack-tailwind.config")
module.exports = (config, env) => {
config = nrwlConfig(config)
return {
...config,
...other config ..
module: {
...config.module,
rules: [...config.module.rules, webpackTailwindConfig.tailwindWebpackRule]
},
node: { ...config.node, global: true }
}
}
webpack-tailwind.config
const tailwindWebpackRule = {
test: /\.scss$/,
loader: "postcss-loader"
}
exports.tailwindWebpackRule = tailwindWebpackRule
and style.scss that import all tailwind
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";

Related

Jest import issue for react js app with custom imports prefix for workerize-loader

I am facing an issue with setting up tests for react app with Jest.
I am using workerize-loader! library to import modules into webworkers.
On tests that use the import worker from workerize-loader!./path/to/file are barking on import of the test. I tried with a custom loader, in the jest.condig.js file but that did not work. When I run the default testing script provided by the react app setup it cannot find the imports in the files. But the code when it runs works alright.
I need help with importing the modules inside of the test suite of jest
Basic test
import React from "react";
import {cleanup, fireEvent, render } from "#testing-library/react";
import App from "./App";);
afterEach(cleanup);
test("basic test", () => {
const { container } = render(<App />);
const linkElement = container.firstChild;
expect(linkElement).toBeInTheDocument();
});
Configuration
jest.config.js
module.exports = {
preset: 'ts-jest',
verbose: true,
testEnvironmentOptions: {
url: 'http://localhost/'
},
testEnvironment: 'jsdom',
transform: {
'workerize-loader(\\?.*)?!(.*)': '<rootDir>/workerize-jest.js',
'^.+\\.(js|jsx)$': 'babel-jest',
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
unmockedModulePathPatterns: [
'node_modules',
],
moduleNameMapper: {
'workerize-loader(\\?.*)?!(.*)': 'identity-obj-proxy'
},
};
.babelrc
{
"plugins": [
"syntax-dynamic-import",
"#babel/transform-runtime"
],
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
]
}
}
}
Error message on react-scripts test
Cannot find module 'workerize-loader!./workers/css.worker'
In file
> 2 | import worker from 'workerize-loader!./workers/css.worker';
workerize-jest.js
module.exports = {
process(src, filename) {
return `
async function asyncify() { return this.apply(null, arguments); }
module.exports = function() {
const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
const m = {};
for (let i in w) m[i] = asyncify.bind(w[i]);
return m;
};
`;
}
};

Next js jest coverage

I am using in my next js application Cypress and Jest. Running jest --coverage i get an error:
STACK: 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'],
]
This is my .babelrc file:
{
"presets": ["next/babel"],
"plugins": ["istanbul"]
}
Who faced with the same issue and how to solve it to get the coverage?
I found the solution that helped to solve the problem.
I had to add the env variable to the .babelrc
{
"env": {
"component": {
"plugins": [
"istanbul"
]
}
}
}
Then add it to cypress.config.js
const { defineConfig } = require('cypress');
const { devServer } = require('#cypress/webpack-dev-server');
const webpackConfig = require('./config/cypress.webpack.config.js');
const codeCoverageTask = require('#cypress/code-coverage/task');
module.exports = defineConfig({
viewportWidth: 1000,
viewportHeight: 660,
video: false,
env: {
BABEL_ENV: 'component',
},
component: {
devServer(devServerConfig) {
return devServer({
...devServerConfig,
framework: 'react',
webpackConfig,
});
},
specPattern: 'src/**/*.cy.{js,ts,jsx,tsx}',
setupNodeEvents(on, config) {
codeCoverageTask(on, config);
return config;
},
},
});

jest with typescript throws an error when importing a file

I'm having issues with jest on typescript.
//myprovider.tsx
class MyProvider{
constructor(){}
giveMeFive(): int{ return 5; }
}
export { MyProvider }
// myprovider.test.js
import { MyProvider } from './myprovider';
test('give me five!', () => {
const myprovider = new MyProvider();
/// assert
})
I get the following error
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
import { MyProvider } from './myprovider';
^
I'm not sure what I'm missing, I have this on my package
//package.json
"jest": {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": ["ts", "tsx", "js"]
},
// .babelrc
{
"presets": [
"#babel/preset-typescript"
]
}
//jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
}
Make sure to install these packages:
babel-jest #babel/core #babel/preset-env
Your babel config should look like this:
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current",
},
},
],
"#babel/preset-typescript",
]

React: ReferenceError: regeneratorRuntime is not defined

I am trying to use async and await in my react application.
onSubmit = async (model) => {
await this.setState({ data: model });
}
After adding the above code i get an error in my browser console.
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
],
"sourceMaps": "inline"
}
webpack.config.js
const path = require("path");
const WebpackShellPlugin = require("webpack-shell-plugin");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = [
{
Server config removed
},
{
entry: {
app1: './src/public/app1/index.js',
app2: './src/public/app2/index.js',
app3: './src/public/app3/index.js',
},
devtool: "source-map",
output: {
path: __dirname + '/dist/public/',
publicPath: '/',
filename: '[name]/bundle.js',
devtoolLineToLine: true,
sourceMapFilename: "[name]/bundle.js.map",
},
module: {
rules: [
{
test: /(\.css|.scss)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
{
test: /\.(jsx|js)?$/,
use: [{
loader: "babel-loader",
// options: {
// cacheDirectory: true,
// presets: ['react', 'es2015'] // Transpiles JSX and ES6
// }
}]
}
],
},
"plugins": [
new CopyWebpackPlugin([
{
from: 'src/public/app1/index.html',
to: 'app1'
},
{
from: 'src/public/app2/index.html',
to: 'app2'
},
{
from: 'src/public/app3/index.html',
to: 'app3'
},
]),
]
}
];
I have added my babelrc and webpack config. Please let me know if i am missing something that would cause this error to appear in my browser console.
Import regeneratorRuntime in the component using async/await:
import regeneratorRuntime from "regenerator-runtime";
*** UPDATED ANSWER *** (probably don't use above)
Import babel and #babel/plugin-transform-runtime plugin:
package.json
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/plugin-transform-runtime": "^7.8.3",
},
.babelrc
{
"plugins": ["#babel/plugin-transform-runtime"]
}
You did not include your package.json file, so it is a bit unclear what you are missing.
Assuming you have #babel/polyfill as a dependency in your package.json file, is it possible that you are not specifying:
import '#babel/polyfill'
in your React file (such as index.js)?
Adding polyfills from create-react-app worked for me.
yarn add --dev react-app-polyfill
Then add the following lines to webpack.config.js
entry: {
app: [
'react-app-polyfill/ie9', // Only if you want to support IE 9
'react-app-polyfill/stable',
'./src/index.jsx',
],
},
See more examples on the react-app-polyfill GitHub page.

Why does Hot Module Replacement stop working on webpack dev server when I setup Babel es2015 preset?

I have a small app running through webpack dev server (on dev environment).
The hot module replacement is running well, I can see my changes on the fly while I edit my js files.
But as soon as I add the es2015 preset in babel loader config, it stops working !
webpack.config.js :
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
process.env.BABEL_ENV = 'development';
module.exports = {
entry: {
app: ['react-hot-loader/patch', path.join(__dirname, 'src')]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'src'),
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['react'],
},
},
}
]
},
devServer: {
historyApiFallback: true,
quiet: true,
hotOnly: true,
contentBase: './build',
host: 'my-host.local',
port: 8091,
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
},
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack demo',
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new FriendlyErrorsWebpackPlugin(),
new webpack.WatchIgnorePlugin([
path.join(__dirname, 'node_modules')
]),
],
};
src/index.js file :
import React from 'react';
import ReactDOM from 'react-dom';
import Component from './Component';
import { AppContainer } from 'react-hot-loader';
const app = document.createElement('div');
document.body.appendChild(app);
const render = App => {
ReactDOM.render(
<AppContainer><App /></AppContainer>,
app
);
};
render(Component);
if (module.hot) {
module.hot.accept('./Component', () => render(Component));
}
Component.js
import React from 'react';
export default class Title extends React.Component {
render() {
return (
<div>Ass</div>
);
}
}
.babelrc
{
"presets": [
[
"react",
"es2015",
{
"modules": false
}
]
],
"env": {
"development": {
"plugins": [
"react-hot-loader/babel"
]
}
}
}
And soon as I replace
presets: ['react'],
by
presets: ['es2015', 'react'],
The Hot Module Replacement feature stops working.. Does anyone has a clue here ?
(also don't hesitate to point at bad practices or avoidable complications in my code)
You need the following .babelrc (I don't know why).
.babelrc
{
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
],
}
Where stage-2 is the npm package babel-preset-stage-2.

Resources