Jest won't transform node_module dependencies - javascript

Our code references the #myScope/vue-notify library which is set as a external/global in our rollup config. That code is an ES6 module and needs to be transpiled for jest to be able to work with it but by default Jest doesn't transpile node_modules folder. I have tried adding a negative lookahead to the transformIgnorePatterns but no matter what combination I try I just keep getting this error:
My Jest transform settings are as follows:
transform: {
'.+\\.(css|css!|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.(js|jsx)?$': 'babel-jest',
},
transformIgnorePatterns: [
'/node_modules/(?!#myScope/vue-notify)',
'/dist/',
'/docs/',
],
My rollup.config.js is as follows:
import packageJson from './package.json';
import json from '#rollup/plugin-json';
import babel from '#rollup/plugin-babel';
import { addMinExtension } from './utils/utils';
import { terser } from 'rollup-plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
const globals = {
DevExpress: 'DevExpress',
jquery: '$',
'#myScope/vue-notify': 'vueNotify',
'file-saver': 'saveAs',
exceljs: 'ExcelJS',
};
const externals = ['jquery', '#myScope/vue-notify', 'file-saver', 'exceljs'];
export default [
{
// Dev UMD Config:
input: packageJson.input,
output: [
{
name: packageJson.moduleName,
file: packageJson.browser,
format: 'umd',
globals: globals,
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
babel({ babelHelpers: 'runtime' }),
],
},
{
// Dev Module Config:
input: packageJson.input,
output: [
{
file: packageJson.module,
format: 'es',
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
],
},
{
// Prod UMD Config:
input: packageJson.input,
output: [
{
name: packageJson.moduleName,
file: addMinExtension(packageJson.browser),
format: 'umd',
sourcemap: true,
globals: globals,
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
babel({ babelHelpers: 'runtime' }),
terser(),
],
},
{
// Prod Module Config:
input: packageJson.input,
output: [
{
file: addMinExtension(packageJson.module),
format: 'es',
},
],
external: externals,
plugins: [
nodeResolve(),
commonjs({
include: 'node_modules/**',
}),
json(),
terser(),
],
},
];
Any help getting this working would be much appriciated!

Related

How to extract all used polyfill from multiple libs by rollup?

I use rollup to create multiple libs, rollup config file as below:
import terser from '#rollup/plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import { babel } from '#rollup/plugin-babel';
import eslint from '#rollup/plugin-eslint';
const distDir = "dist/libs"
const api = {
input: "src/libs/api/index.js",
external: ["axios"],
output: [
{
file: `${distDir}/api.umd.js`,
format: "umd",
name: 'Api',
globals: {axios: 'axios'}
},
{
file: `${distDir}/api.es.js`,
format: "es"
}
],
plugins: [
terser(),
babel({babelHelpers: 'runtime', exclude: 'node_modules/**'}),
nodeResolve({
browser:true,
}),
commonjs(),
eslint({
throwOnError: true,
throwOnWarning: true,
include: ['src/**'],
exclude: ['node_modules/**']
})
]
}
const test = {
...
}
export default ()=>{
return [
api, // it contains some polyfill
test // it also contains some polyfill
]
};
My .babelrc is:
{
"presets": [
["#babel/preset-env", {
"corejs": {"version": "3", "proposals": false},
"useBuiltIns": "usage"
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime"
]
]
}
Now, api and test contain some polyfill. Is there a way to extract the used polyfills of all modules to form a single umd file but not Full Function polyfill.Thank you.

Rollup library ERROR in resolving fallback for shared module react

I am creating a design system library with rollup and React 17.0.1, unfortunatelly I am getting this error when I use the library
Error: Can't resolve 'react/jsx-runtime'
The rollup file is this
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
exports: "auto",
sourcemap: false,
preserveModules: false
},
{
file: packageJson.module,
format: 'esm',
sourcemap: false
}
],
plugins: [
svgr(),
json(),
url(),
peerDepsExternal(),
resolve({
jsnext: true,
main: true,
browser: true
}),
babel({
babelrc: true,
exclude: 'node_modules/**',
presets: [
["#babel/preset-react", { runtime: "automatic" }],
]
}),
commonjs({
include: "node_modules/**",
namedExports: {
'styled-components': [ 'styled', 'css', 'ThemeProvider' ],
"react/jsx-runtime": ["jsx", "jsxs", "Fragment"],
"react/jsx-dev-runtime": ["jsxDEV", "Fragment"]
}
}),
typescript({ useTsconfigDeclarationDir: true }),
postcss(),
progress(),
visualizer({})
],
external: [...Object.keys(packageJson.peerDependencies || {})]
},
{
input: 'types/index.d.ts',
output: [{ file: 'dist/index.d.ts', format: "esm" }],
external: [/\.css$/],
plugins: [dts()],
},
]
I looked for lots of solutions but I cannot find any good one... may you help me? Thanks
Lorenzo
It may help. "#rollup/plugin-node-resolve" plugin.
resolve({ extensions: [".js", ".jsx"] })
(tsx and ts if you are using typescript)
please let me know if it didnt help :)

Is there a way for exporting multiple default react components from a react package in rollupjs?

I want to achieve to have multiple default exports. For example, if a react app installs my package named {my-package} then, they should be be able to import like
import Add from {my-package}/Add;
import Multiply from {my-package}/Multiple;
I've tried with making multiple end points in rollup.config.js.
`
export default [
{
input: files,
output: [
{
format: 'cjs',
strict: false,
// file: pkg.main,
dir: pkg.main,
sourcemap: true,
exports: 'named'
},
{
format: 'esm',
strict: false,
dir: pkg.module,
sourcemap: true,
exports: 'named'
}
],
plugins: [
commonjs(),
nodePolyfills(),
nodeResolve({ browser: true }),
image(),
json(),
postcss({
config: {
path: './postcss.config.js'
},
extensions: ['.css', '.scss'],
minimize: true,
inject: {
insertAt: 'top'
},
plugins: [url({ url: 'inline', maxSize: 10, fallback: 'copy' })]
}),
babel({ exclude: 'node_modules/**', presets: ['#babel/preset-react'] }),
typescriptPlugin({
objectHashIgnoreUnknownHack: true,
tsconfig: './tsconfig.json'
}),
cleaner({ targets: ['./dist/'] })
],
external: [
'react',
'react-dom',
'js-beautify',
'next-themes',
'react-split',
'react-codemirror2',
'react-responsive-modal',
'pinterpolate'
]
}
];
`
This is my rollup.config.js
Is it possible witn rollupjs?

module is not defined at node_modules/core-js/internals/global.js

I'm building a library in TypeScript, and I'm trying to test it. As It involves browser API I'm testing it using #web/test-runner and chai.
I'm using TypeScript, and some libraries are commonjs modules, so I'm using Rollup to bundle all of that into something the browser can use.
My rollup config is as follow:
import typescript from '#rollup/plugin-typescript';
import commonjs from '#rollup/plugin-commonjs';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import json from '#rollup/plugin-json';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { babel } from '#rollup/plugin-babel';
import nodePolyfills from 'rollup-plugin-node-polyfills';
const pkg = require('./package.json');
const libraryName = 'AGreatLibrary';
export default {
input: 'src/index.ts',
output: [
{ file: pkg.main, name: libraryName, format: 'umd', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
plugins: [
json(),
nodePolyfills(),
typescript(),
commonjs(),
nodeResolve({ browser: true, preferBuiltins: false }),
sourceMaps(),
babel({ babelHelpers: 'bundled', exclude: [/\bcore-js\b/, /\bwebpack\/buildin\b/] }),
],
};
My babel config
{
"presets":
[
[
"#babel/env",
{
"targets":
{
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3"
}
]
],
"minified": true
}
My test file
import { Client } from "../lib/index.es.js";
import { expect } from '#esm-bundle/chai';
it('Should create a Client', () => {
let client = new Client("123", true);
expect(client.accessToken).to.equal("123");
});
it('Should auth', async () => {
let client = new Client("123", true);
let resp = await client.tryAuth();
expect(resp.ok).to.be.true;
});
But when I run my test (web-test-runner "test/**/*.test.ts" --node-resolve)
I get the following error
🚧 Browser logs:
ReferenceError: module is not defined
at node_modules/core-js/internals/global.js:6:0
I have no idea what to do.
I fix it!
plugins: [
commonjs(),
json(),
nodePolyfills(),
typescript(),
nodeResolve({ browser: true, preferBuiltins: false }),
sourceMaps(),
babel({ babelHelpers: 'bundled', exclude: [/\bcore-js\b/, /\bwebpack\/buildin\b/] }),
],
commonjs should be on top of the array.

"Parsing error: invalid character" when bundling images with Webpack's loaders

When I'm trying to bundle my React project, I get the following error regarding an image I'm about to load:
Oddly enough, when I hide the error overlay, I can see in a browser that my picture has been loaded correctly, despite Webpack's complaints. I've already been carefully following other working config examples, where that problem doesn't occur, but I can't easily identify the source of the issue, what leaves me here with no idea how to approach it or where to look for a hint. I've also tried different loaders: url-loader, file-loader and image-webpack-loader, but to no avail. Maybe that's Typescript what causes these troubles?
App.tsx where I'm importing my image:
import "./app.d";
import React from "react";
import SampleImage from "./assets/images/sample-image.jpg";
const App: React.FC = () => (
<div>
<img src={SampleImage} />
</div>
);
export default App;
app.d.ts with modules declarations to allow importing assets in typescripts files:
declare module "*.jpeg";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.png";
webpack.common.ts - my main Webpack config file, where I placed both url-loader and file-loader as it is in ejected create-react-app config, but it doesn't really change anything:
import path from "path";
import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import { CleanWebpackPlugin } from "clean-webpack-plugin";
module.exports = {
entry: path.resolve(__dirname, "..", "./src/index.tsx"),
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve("babel-loader"),
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
],
},
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.(ts|tsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve("file-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]",
},
include: path.resolve(__dirname, "..", "./src/assets"),
},
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]",
},
include: path.resolve(__dirname, "..", "./src/assets"),
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "..", "./dist"),
filename: "bundle.js",
},
devServer: {
contentBase: path.resolve(__dirname, "..", "./dist"),
hot: true,
compress: true,
open: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "React App",
template: path.resolve(__dirname, "..", "./src/index.html"),
}),
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*"),
},
}),
],
};
webpack.dev.ts
import webpack from "webpack";
import ReactRefreshWebpackPlugin from "#pmmmwh/react-refresh-webpack-plugin";
module.exports = {
mode: "development",
devtool: "eval-source-map",
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve("babel-loader"),
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
plugins: [require.resolve("react-refresh/babel")],
},
},
],
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ReactRefreshWebpackPlugin({
overlay: {
sockIntegration: "wds",
},
}),
],
};
webpack.prod.ts
import webpack from "webpack";
module.exports = {
mode: "production",
devtool: "source-map",
};
webpack.config.ts
import merge from "webpack-merge";
import devConfig = require("./webpack.dev");
import prodConfig = require("./webpack.prod");
import commonConfig = require("./webpack.common");
module.exports = ({ env }: { env: "dev" | "prod" }) => {
const envConfig = env === "dev" ? devConfig : prodConfig;
return merge(commonConfig, envConfig);
};
Additionaly, my .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
"react-refresh/babel",
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
and tsconfig.json:
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["src"]
}
Scripts in package.json:
"scripts": {
"start": "webpack serve --config config/webpack.config.ts --env env=dev --hot",
"build": "webpack --config config/webpack.config.ts --env env=prod",
},
I'd be really grateful for any hint how to solve the issue.
Thanks to help received here: https://github.com/webpack/webpack/issues/12276#event-4152056913, I've managed to surpass the error overlay by changing the options passed to the ForkTsCheckerWebpackPlugin in my webpack.common.ts file.
Before:
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*"),
},
}),
Now:
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*.{ts,tsx,js,jsx}"),
},
}),

Categories

Resources