How to use redux-form in peer dependency - reactjs

I am trying to create a ES6 module of a login form using rollup and react-redud.
I have a rollup with the following configuration:
const plugins = [
// Unlike Webpack and Browserify, Rollup doesn't automatically shim Node
// builtins like `process`. This ad-hoc plugin creates a 'virtual module'
// which includes a shim containing just the parts the bundle needs.
{
resolveId(importee) {
if (importee === processShim) return importee;
return null;
},
load(id) {
if (id === processShim) return 'export default { argv: [], env: {} }';
return null;
},
},
nodeResolve(),
commonjs({
include: 'node_modules/**',
namedExports: {
'./node_modules/immutable/dist/immutable.js': ['fromJS', 'Map', 'List', 'Record', 'Iterable'],
'./node_modules/redux/dist/redux.js': ['createStore', 'combineReducers', 'bindActionCreators', 'applyMiddleware', 'compose'],
'./node_modules/react-redux/dist/react-redux.js': [' Provider', 'createProvider', 'connectAdvanced', 'connect'],
},
}),
replace({
'process.env.NODE_ENV': JSON.stringify(prod ? 'production' : 'development'),
}),
inject({
process: processShim,
}),
json(),
babel({
plugins: ['external-helpers'],
exclude: 'node_modules/**',
}),
cleanup(),
];
if (prod) plugins.push(uglify(), visualizer({ filename: './bundle-stats.html' }));
export default {
input: 'src/index.js',
sourcemap: true,
name: pkg.name,
external: ['react', 'react-dom', 'prop-types', 'styled-components', 'bootstrap-styled', 'classnames', 'react-transition-group', 'loaders', 'redux-form', 'redux', 'react-redux', 'react-intl', 'message-common', 'bootstrap-styled-motion'],
exports: 'named',
output,
plugins,
globals: { react: 'React', 'react-dom': 'ReactDom', 'prop-types': 'PropTypes', 'styled-components': 'styled', classnames: 'cn', 'react-transition-group': 'ReactTransitionGroup', loaders: 'loaders', 'redux-form': 'redux-form', 'react-intl': 'react-intl', 'message-common': 'message-common' },
};
My rollup bundle fine, no warnings.
I have tried every possibility of import :
import reduxForm from 'redux-form/lib/immutable/reduxForm';
import Field from 'redux-form/lib/immutable/Field';
and
import { Field, reduxForm } from 'redux-form/es/immutable';
and
import { Field, reduxForm } from 'redux-form/es/immutable';
But nothing work, everytime I install this module somewhere, the transpiled ES replace this line with these imports
import reactRedux from 'react-redux';
import redux from 'redux';
I assume this is happening because redux-form depend on these two. Because these two modules doesn't have default export, this throw an error :
WARNING in ./node_modules/login-form/dist/login-form.es.js
3471:19-24 "export 'default' (imported as 'redux') was not found in 'redux'
WARNING in ./node_modules/login-form/dist/login-form.es.js
3524:26-36 "export 'default' (imported as 'reactRedux') was not found in 'react-redux'
I have tried to play with globals, namedExports. I haven't found a way to make redux-form a peer of my project.

I finally solved it and I had to set my externals with redux-form/immutable instead of just redux-form

Related

Vitest config doesn't detect jsdom environment

I'm in a Vite/React/TypeScript application and I'm configuring my first test with Vitest.
When I run my Button test (yarn vitest), I get this error:
packages/frontend/src/components/Generic/Button/Button.test.tsx > Button > should render the button
ReferenceError: document is not defined
I understand that Vitest does not work with JSDom. I have tried several things:
KO: Specifying in the vite.config.ts file to use JSDom
OK: Adding a vitest.config.ts file specifying to use JSDom
OK: Adding an annotation (#vitest-environment jsdom) at the top of the test file
I would prefere use the first option (use vite.config.ts) to share only one configuration. Is it possible ?
Note 1 : JSdom i already installed has "devDependencies".
Note 2 : to use vitest.config.ts i should update the script in package.json like that :
"test": "vitest --config ./packages/frontend/vitest.config.ts"
Here are my files:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import viteTsConfigPaths from 'vite-tsconfig-paths'
import tailwindcss from 'tailwindcss'
export default defineConfig({
server: {
port: 4200,
host: 'localhost',
},
rollupOption: {
external: ['#internals/components/index']
},
define: {
global: {},
},
plugins: [
react(),
tailwindcss(),
viteTsConfigPaths({
root: '../../',
}),
],
resolve: {
alias: {
// runtimeConfig is a special alias that is used to import the correct config file
'./runtimeConfig': './runtimeConfig.browser',
// public alias
'#publics': `${__dirname}/public`,
// only internals (private) aliases are allowed here
'#internals/components': `${__dirname}/src/components`,
'#internals/features': `${__dirname}/src/features`,
'#internals/hooks': `${__dirname}/src/hooks`,
'#internals/models': `${__dirname}/src/models`,
'#internals/utils': `${__dirname}/src/utils`,
'#internals/types': `${__dirname}/src/types`,
'#internals/styles': `${__dirname}/src/styles`,
'#internals/assets': `${__dirname}/src/assets`,
'#internals/store': `${__dirname}/src/store`,
'#internals/config': `${__dirname}/src/config`,
'#internals/services': `${__dirname}/src/services`,
},
},
test: {
globals: true,
cache: {
dir: '../../node_modules/.vitest',
},
environment: 'jsdom',
include: ['*.tsx', '*.ts', '*.jsx', '*.js'],
},
})
I tried to add a like this vitest.config.ts :
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['*.ts', '*.tsx'], // FIXME
environment: 'jsdom',
},
})

Fail to integrate scss in my rollup build

What I try to achieve
I'm trying to create a little library for private use - basically just splitting up some code into lib (product) and app (project) code.
All my source code lives in /src folder which contains React, TypeScript and SCSS code. It would be great, if I can use the SCSS imports directly in React like: import './_button.scss';
I have another SCSS file: src/style/_main.scss it includes some mixins, global styles, resets etc.
Config files
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import resolve from '#rollup/plugin-node-resolve';
import terser from '#rollup/plugin-terser';
import typescript from '#rollup/plugin-typescript';
import url from '#rollup/plugin-url';
import dts from 'rollup-plugin-dts';
import scss from 'rollup-plugin-scss';
import { format, parse } from 'path';
import pkg from './package.json' assert { type: 'json' };
const getTypesPath = (jsFile) => {
const pathInfo = parse(jsFile);
return format({
...pathInfo,
base: '',
dir: `${pathInfo.dir}/types`,
ext: '.d.ts',
});
};
export default [
{
input: 'src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
interop: 'compat',
exports: 'named',
sourcemap: true,
inlineDynamicImports: true,
},
{
file: pkg.module,
format: 'esm',
exports: 'named',
sourcemap: true,
inlineDynamicImports: true,
},
],
plugins: [
resolve({ browser: true }),
commonjs({ extensions: ['.js', '.jsx', '.ts', '.tsx'] }),
typescript({ tsconfig: './tsconfig.build.json' }),
url(),
scss({
failOnError: true
}),
json(),
terser(),
],
external: ['react', 'react-dom'],
},
{
input: getTypesPath(pkg.module ?? pkg.main),
output: [{ file: pkg.types, format: 'esm' }],
plugins: [dts()],
},
];
My tsconfig.build.json looks like this:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./types",
"declaration": true,
"declarationDir": "./types",
"allowSyntheticDefaultImports": true
}
}
Where I struggle
The main issue right now is, that it imports my SCSS file in the definition file e.g. button.d.ts looks like:
import type { FunctionComponent } from 'react';
import type { IButtonProps } from './button.type';
import './_button.scss';
export declare const Button: FunctionComponent<IButtonProps>;
[!] RollupError: Could not resolve "./_button.scss" from "build/esm/types/button/button.d.ts"
Which is indeed a problem, but how can I fix it?
I also get the error:
Error:
#use rules must be written before any other rules.
╷
4 │ #use 'src/style/util/mixin';
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
╵
stdin 4:1 root stylesheet
But it does not really make a lot of sense, since my _button.scss partial has this written on the first line.
My Question
How do I make it work so that I can use SCSS in my library? The best case would be that I don't have to touch my original code. I just want to transpile/bundle it so I can use it somewhere else. Any advice?
After hours of probing, I finally made it work.
The issue was, that it bundled all my sass styles and it did not take into account, that I am using the new #use module syntax. Because everything got concatenated into one big file, #use syntax got placed in the middle of the file resulting in an error. Apparently, only the old #import syntax is properly supported by rollup-plugin-scss - or I was just too incapable of making it work.
So I switched to the https://anidetrix.github.io/rollup-plugin-styles/
library to process the files. All I had to do is to use the styles plugin and I set mode: 'inject' it then injected the styles into my [esm|cjs]/index.js file. Upon importing the lib in the app and starting it, the styles got applied.
Besides, I also had to externalize the imports from the index.d.ts.
The updated config file:
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import resolve from '#rollup/plugin-node-resolve';
import terser from '#rollup/plugin-terser';
import typescript from '#rollup/plugin-typescript';
import url from '#rollup/plugin-url';
import { format, parse } from 'path';
import dts from 'rollup-plugin-dts';
import external from 'rollup-plugin-peer-deps-external';
import styles from 'rollup-plugin-styles';
import pkg from './package.json' assert { type: 'json' };
const getTypesPath = (jsFile) => {
const pathInfo = parse(jsFile);
return format({
...pathInfo,
base: '',
dir: `${pathInfo.dir}/types`,
ext: '.d.ts',
});
};
export default [
{
input: 'src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
interop: 'compat',
exports: 'named',
sourcemap: true,
inlineDynamicImports: true,
},
{
file: pkg.module,
format: 'esm',
exports: 'named',
sourcemap: true,
inlineDynamicImports: true,
},
],
external: ['react', 'react-dom'],
plugins: [
external(),
resolve({
browser: true,
}),
url(),
styles({
mode: 'inject'
}),
json(),
commonjs({
extensions: ['.js', '.jsx', '.ts', '.tsx'],
}),
typescript({
tsconfig: './tsconfig.build.json',
}),
terser(),
],
},
{
input: getTypesPath(pkg.module ?? pkg.main),
output: [
{
file: pkg.types,
format: 'esm',
},
],
external: [/\.(sass|scss|css)$/] /* ignore style files */,
plugins: [dts()],
},
];

css module support using react Rolllup

I'm working on building out a react package (not app) and have run into my introduction to using rollup which, as I understand it, the equivalent to using webpack for react app development.
As I'm moving my code over I've run into a snag where I can't seem to work out the configuration to allow for css/scss module support, e.g.,
import React from "react";
import styles from "./Button.css"; <--- TS2307: Cannot find module './Button.css' or its corresponding type declarations.
my configuration looks like this:
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "#rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";
const packageJson = require("./package.json");
export default [
{
input: "./src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true
},
{
file: packageJson.module,
format: "esm",
sourcemap: true
}
],
plugins: [
resolve(),
postcss({
extract: false,
modules: true,
use: ['sass'],
}),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" })
]
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
external: [/\.(css|less|scss)$/]
}
];
but I can't get passed the error:
TS2307: Cannot find module './Button.css' or its corresponding type declarations.
my web research has found some attempts at solving this, but nothing has worked. I can drop the css directly on the component:
import React from "react";
import "./Button.css";
But the assignment doesn't work. Any ideas on solution?

Rollup ESM generates broken imports

I want to bundle a typescript react App as a component into a ES module or UMD.
But the generated ES bundle produces an invalid module js.
On bundle it gives me this hints. But I cant find any solution for this.
(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
http (guessing 'http')
...
inside the esm js bundle there are imports like these:
import http from 'http';
import https from 'https';
import url from 'url';
import require$$0 from 'stream';
...
function createCommonjsModule(fn) {
var module = { exports: {} };
return fn(module, module.exports), module.exports;
}
And after adding it to the browser:
<script type="module" src="./index.esm.js"></script>
I got the error about the missing relative imports:
Uncaught TypeError: Failed to resolve module specifier "http". Relative references must start with either "/", "./", or "../".
Iam surely have mistakes on my rollup configuration, but I cant find the spot and happy and thankful about any hints.
...
Of course I have nodemodule imports in my app like:
import {observer} from 'mobx-react';
But rollup should handle this. Dont he?
Here is my rollup.config:
import pkg from './package.json';
import nodeResolve from "#rollup/plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import image from "#rollup/plugin-image";
import styles from "rollup-plugin-styles";
import commonjs from "#rollup/plugin-commonjs";
import replace from "#rollup/plugin-replace";
import json from '#rollup/plugin-json';
import babel from '#rollup/plugin-babel';
import copy from "rollup-plugin-copy";
import del from "rollup-plugin-delete";
export default {
input: pkg.source,
output: [
{
file: pkg.module,
format: 'es',
sourcemap: false
},
{
file: "dist/index.umd.js",
format: 'umd',
sourcemap: true
},
],
plugins: [
del({targets: 'dist/*'}),
nodeResolve({
mainFields: ['jsnext:main', 'module', 'main'],
dedupe: [ 'react', 'react-dom' ]
}),
replace({
preventAssignment: false,
'process.env.NODE_ENV': JSON.stringify('development'),
__buildDate__: () => JSON.stringify(new Date())
}),
json(),
typescript(),
styles(),
copy({
targets: [
{src: 'public/**/*', dest: 'dist'}
]
}),
babel({ //disabled cause WebComponent integration
presets: ["#babel/preset-react"],
exclude: 'node_modules/**',
babelHelpers: 'bundled'
}),
commonjs(),
image()
]
};
I had a similar issue (though with stream module, not http), and for me the solution was to set browser: true in nodeResolve within rollup.config:
export default [
{
input: '...',
plugins: [
nodeResolve({
'browser': true,
}),
commonjs(),
],
output: {
...
}
}
];
From description of a flag:
browser
Type: Boolean
Default: false
If true, instructs the plugin to use the browser module resolutions in package.json and adds 'browser' to exportConditions if it is not present so browser conditionals in exports are applied. If false, any browser properties in package files will be ignored. Alternatively, a value of 'browser' can be added to both the mainFields and exportConditions options, however this option takes precedence over mainFields.

rollup MISSING_NODE_BUILTINS error when I include it

I keep getting this error:
src/legacy/widgetlib.tsx → dist/withReact16/browser.js...
{
code: 'MISSING_NODE_BUILTINS',
message: "Creating a browser bundle that depends on Node.js built-in module ('punycode'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins",
modules: [ 'punycode' ],
toString: [Function]
}
I have included rollup-plugin-node-builtins in multiple different ways and I've googled all over the place. Every "solution" I've found seems to basically be the same thing, but it isn't working for me. I am also not even directly using punycode. Two of my dependencies have it as a dependency. I am using twitter-text lib and oauth-signature. If I comment out those two imports I no longer get this problem. Here is my complete rollup.config.js file:
import resolve from '#rollup/plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import commonjs from '#rollup/plugin-commonjs';
import babel from 'rollup-plugin-babel';
import json from '#rollup/plugin-json';
import image from '#rollup/plugin-image';
import replace from 'rollup-plugin-replace';
import gzipPlugin from 'rollup-plugin-gzip';
import { terser } from 'rollup-plugin-terser';
import includePaths from 'rollup-plugin-includepaths';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import React from 'react';
import ReactDOM from 'react-dom';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
const { PRODUCTION } = process.env;
const CODES = [
'THIS_IS_UNDEFINED',
'MISSING_GLOBAL_NAME',
'CIRCULAR_DEPENDENCY',
];
const globalVars = {
react: 'React',
'react-dom': 'ReactDOM',
};
const discardWarning = warning => {
if (CODES.includes(warning.code)) {
return;
}
// eslint-disable-next-line no-console
console.error(warning);
};
const commonConfig = {
onwarn: discardWarning,
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify(
PRODUCTION ? 'production' : 'development'
),
}),
image(),
globals(),
builtins(),
resolve({
jsnext: true,
extensions,
preferBuiltins: true,
browser: true,
mainFields: ['browser', 'jsnext', 'module', 'main'],
}),
includePaths({
paths: ['src'],
extensions: [...extensions, '.scss', '.json'],
}),
commonjs({
include: 'node_modules/**',
namedExports: {
react: Object.keys(React),
'react-dom': Object.keys(ReactDOM),
},
}),
babel({
extensions,
runtimeHelpers: true,
babelrc: true,
exclude: 'node_modules/**',
}),
json(),
postcss({
plugins: [],
}),
terser(),
],
};
const browserLibWithReact16 = {
...commonConfig,
input: 'src/legacy/widgetlib.tsx',
output: {
format: 'iife',
sourcemap: true,
name: 'WLIB',
file: 'dist/withReact16/browser.js',
},
plugins: [...commonConfig.plugins, gzipPlugin()],
};
const npmWLIBWithReact16 = {
...commonConfig,
input: 'src/widgetlib.tsx',
output: {
file: 'dist/withReact16/WLIB.js',
format: 'esm',
sourcemap: true,
},
};
const npmLibNoReact = {
...commonConfig,
external: Object.keys(globalVars),
input: 'src/widgetlib.tsx',
output: {
file: 'dist/index.js',
format: 'esm',
sourcemap: true,
},
};
export default [npmLibNoReact, npmWLIBWithReact16, browserLibWithReact16];
The error is only happening for the browserLibWithReact16 config.
Any help would be appreciated.

Resources