I have a problem on build my project react with typescript, on import in another project the types doesn't work, have a message 'process not defined'.
//package.json
...
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"types": ".lib/cjs/types.d.ts",
...
Initial i'm using this configurations to building the lib.
//tsconfig.base.ts
{
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"checkJs": true,
"allowJs": true,
"declaration": true,
"allowSyntheticDefaultImports": true,
"jsx": "react-jsx"
},
"include": ["../src", "../public"],
"exclude": [
"../src/stories",
"../node_modules",
"../lib",
"../src/stories",
"../src/tests",
"../src/components/modals"
]
}
//tsconfig.cjs.ts
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"lib": ["ES6", "DOM"],
"target": "ES6",
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "../lib/cjs",
"declarationDir": "../lib/cjs"
}
}
//tsconfig.esm.ts
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2022", "DOM"],
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Node",
"outDir": "../lib/esm",
"declarationDir": "../lib/esm"
}
}
Im another try, i'm used rollup to build but doesn't worked too.
//rellup-cjs.config.mjs
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import typescript from '#rollup/plugin-typescript';
import css from 'rollup-plugin-import-css';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import terser from '#rollup/plugin-terser';
export default {
input: './src/index.tsx',
output: {
dir: './lib/cjs/',
format: 'cjs',
sourcemap: true,
exports: 'auto',
preserveModules: true,
},
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({ tsconfig: './tsconfig.json', outDir: './lib/cjs/' }),
css(),
terser(),
],
};
//rellup-esm.config.mjs
...
export default {
...
output: {
dir: './lib/esm/',
format: 'esm',
sourcemap: true,
exports: 'auto',
preserveModules: true,
},ugins: [
...
typescript({ tsconfig: './tsconfig.json', outDir: './lib/cjs/' }),
...
],
};
This the exports of my project:
exports-img
I'm tried to be use rollup or any typescript configurations, but nothing work, I'm made this lib using chakra-ui and others external libs.
Related
Im getting this error out of nowhere.
Code works fine in while im using it, but during testing with Jest this pops up.
......................................................................................................................................................................................................................................................................................................................................................................................................................
Details:
C:\node_modules\react-leaflet\lib\index.js
:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { us
eMap, useMapEvent, useMapEvents } from './hooks.js';
^^^^^^
SyntaxError: Unexpected token 'export'
9 | } from 'react-leaflet';
10 | import { private } from 'private';
> 11 |
| ^
This is my jest config
module.exports = {
moduleNameMapper: {
// Resolve .css and similar files to identity-obj-proxy instead.
'.+\\.(css|styl|less|sass|scss)$': 'identity-obj-proxy',
// Resolve .jpg and similar files to __mocks__/file-mock.js
'.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/file-mock.js',
},
clearMocks: true,
coverageDirectory: 'coverage',
// In jest.config.js add (if you haven't already)
setupFilesAfterEnv: ['./src/setupTests.js'],
coverageProvider: 'v8',
globals: {
'ts-jest': {
isolatedModules: true,
},
},
rootDir: '.',
moduleDirectories: ['node_modules', 'src', 'utils'],
testEnvironment: 'jsdom',
testTimeout: 20000,
roots: ['<rootDir>/src'],
testMatch: [
'**/__tests__/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)',
],
transform: {
'^.+\\.js?$': 'babel-jest',
'^.+\\.(t|j)sx?$': ['#swc/jest'],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: [`/node_modules/(?!${esModules}')`],
};
TsConfig
"include": [
"src/**/*.ts",
"src/**/*.tsx",
],
"exclude": [
"node_modules",
"dist"
],
"compilerOptions": {
"target": "es2015",
"module": "esnext",
"declaration": true,
"lib": [
"es2021",
"es2017",
"es2015",
"dom",
"ESNext"
],
"allowJs": false,
"jsx": "react-jsx",
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"removeComments": true,
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": "src",
"paths": {
"test-utils": [
"./utils/test-utils"
]
}
}
}
.Bablerc & config
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
module.exports = {
presets: [
[
'#parcel/babel-preset-env',
{
targets: {
esmodules: true,
},
},
],
],
};
Is there something that could be causing this or am I missing something else?
The solution ended up being
const esModules = ['#react-leaflet', 'react-leaflet'].join('|');
above the jest.config.js
and in the config
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
I have this mock within a mocks folder (React project). This file is named as getEnvironmentContextMock.ts
import { getEnvironmentContext } from "../apis/environmentStrategy";
const getEnvironmentContextMock = jest
.fn(getEnvironmentContext)
.mockReturnValue({
identity: process.env.REACT_APP_URL_IDENTITY,
company: process.env.REACT_APP_URL_SUBSCRIPTION,
client: process.env.REACT_APP_URL_CLIENTS,
orders: process.env.REACT_APP_URL_ORDER,
});
export { getEnvironmentContextMock };
And when I try to generate the build for production
Exclude node_modules
NODE_ENV=production
npm i
NODE_ENV=production
npm run build --prod
I have the following error within the mock file:
Cannot find name 'jest'. TS2304
My jest.config file
/** #type {import('#ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
globals: {
"ts-jest": {
isolatedModules: true,
},
},
transform: {
"^.+\\.jsx?$": "babel-jest",
"^.+\\.tsx?$": "ts-jest",
},
// Runs special logic, such as cleaning up components
// when using React Testing Library and adds special
// extended assertions to Jest
setupFilesAfterEnv: ["#testing-library/jest-dom/extend-expect"],
moduleNameMapper: {
"\\.(css|less|sass|scss)$": "identity-obj-proxy",
"\\.(png|jpg|gif|ttf|eot|svg)$": "identity-obj-proxy",
},
moduleDirectories: ["js", ".", "node_modules"],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
And my tsconfig file
{
"compilerOptions": {
"target": "es2016",
"module": "esnext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"lib": ["dom", "dom.iterable", "esnext"],
"noImplicitAny": false,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"types": ["jest"],
"typeRoots": ["./types", "./node_modules/#types"]
},
"include": ["src"],
"exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"]
}
Any thoughts on how to fix that?
The build works if I change the mock file name extension to test.tsx, but I don't it as it is not a test file, just a mock file.
Im trying to build my lib and export the components like MaterialUI way:
But, the only thing I can do, is that:
Im using rollup.js and typescript. I notice that d.ts and type.ts files have been exported in the component folder but the component itself is exported in main folder.
Can someone help me to fix it?
My rollup.js config:
import commonjs from '#rollup/plugin-commonjs'
import resolve from '#rollup/plugin-node-resolve'
import replace from '#rollup/plugin-replace'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
import typescript from 'rollup-plugin-typescript2'
import postcss from 'rollup-plugin-postcss'
import { terser } from 'rollup-plugin-terser'
import del from 'rollup-plugin-delete'
import includePaths from 'rollup-plugin-includepaths'
/* css imports */
import pkg from './package.json'
export default {
input: ['./src/index.ts', './src/TestComponent/index.tsx'],
output: [
{
dir: 'dist/esm',
format: 'esm',
sourcemap: true,
exports: 'named',
strict: false,
plugins: [terser()]
}
],
plugins: [
includePaths({ paths: ['./src'] }),
typescript({
}),
peerDepsExternal(),
resolve(),
commonjs(),
del({
targets: ['dist/*']
}),
postcss({
modules: true,
extract: false,
namedExports: true,
writeDefinitions: true,
}),
replace({
preventAssignment: true,
ENV: JSON.stringify(process.env)
}),
],
external: Object.keys(pkg.peerDependencies)
}
My tsconfig.json file:
{
"compilerOptions": {
"declaration": true,
"declarationDir": "dist",
"outDir": "dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom", "es2016", "es2017"],
"sourceMap": true,
"allowJs": false,
"jsx": "react",
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"plugins": [{ "name": "typescript-plugin-css-modules" }]
},
"include": ["src/**/*"],
"exclude": [
"node_modules",
"dist",
"src/**/*.stories.tsx",
"src/**/*.test.tsx"
]
}
My folder's structure:
Ps: I'd like to export only the components to import like
import TestComponent from '#ind/package/esm/TestComponent'
and
import {TestComponent} from '#ind/package/esm'
Late reply, but for anyone stumbling on this the most straightforward way I found was to use the preserveModules option: Instead of creating as few chunks as possible, this mode will create separate chunks for all modules using the original module names as file names.
It does respects the file's relative path, components/Test.jsx ends up in dist/components/Test.js.
This issue also suggests you can map things in input directly; but that doesn't seem to work when using rollup programmatically:
export default {
input: {
'module1': 'src/module1.js',
'foo/module2': 'src/foo/module2.js',
'foo/bar/module3': 'src/foo/bar/module3.js',
},
output: {
format: cjs,
dir: 'dist'
}
}
I configured babel-plugin-module-resolver in my ReactJS project, i use it coupled to TypeScript.
so, I have my .babelrc :
{
"presets": [
"#babel/preset-typescript",
["#babel/preset-env", {"modules": false}],
"#babel/preset-react"
],
"plugins": [
[
"module-resolver",
{
"root": ["./src"],
"alias": {
"#modules": "./modules",
"#screens": "./screens",
"#components": "./components",
"#themes": "./themes",
"#images": "./images"
}
}
]
],
"env": {
"test": {
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
}
}
and then my tsconfig.json
{
"compilerOptions": {
"esModuleInterop": true,
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"allowJs": true,
"pretty": true,
"allowSyntheticDefaultImports": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": ".",
"moduleResolution": "node",
"module": "commonjs",
"target": "es6",
"jsx": "react",
"lib": ["es6", "dom"],
"paths": {
"#modules/*": ["src/modules/*"],
"#screens/*": ["src/screens/*"],
"#components/*": ["src/components/*"],
"#themes/*": ["src/themes/*"],
"#images/*": ["src/images"]
}
},
"exclude": ["node_modules"]
}
For more details of my files architecture, it look like
this
In my file routes.tsx I try to import theme modules
import React from 'react'
import { BrowserRouter, Route as Road, Switch } from 'react-router-dom'
import { Route } from '#modules/types/navigations'
import { Main } from '#themes/ui/theme'
It return the next error : Module not found: Error: Can't resolve '#themes/ui/theme' in project\src
The import work for import { Route } from '#modules/types/navigations' but not for import { Main } from '#themes/ui/theme'
The following code of theses files is
(theme.ts)
import styled from 'styled-components'
export const Main = styled.div`
background: #000
`
(navigations.ts)
export interface Route {
path: string,
exact?: boolean,
children: JSX.Element
}
I tried many path change in .babelrc/tsconfig.json but i dont understand why my modules imports doesn't work apart #modules
Thank you in advance!
I'm building an Angular library with ng-packagr.
When serving my app with the packed library used, I get this warning:
. Furthermore, when serving the app, I get this errormessage:
core_1 is imported alongside other modules in the top:
import core_1, { Component, Inject, Injectable, InjectionToken, NgModule } from '#angular/core';
UPDATE!!
The configuration is as follows:
ng-package.json
{
"$schema": "./node_modules/ng-packagr/ng-package.schema.json",
"src": "lib",
"dest": "dist/auth",
"workingDirectory": ".ng_build",
"lib": {
"entryFile": "public_api.ts",
"externals": {
"oidc-client": "./node_modules/oidc-client/dist/oidc-client.min.js",
"rxjs/add/operator/let": "Rx.Observable.prototype"
}
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"lib": [
"es6",
"dom"
],
"moduleResolution": "node",
"declaration": true,
"experimentalDecorators": true,
"baseUrl": ".",
"stripInternal": true,
"outDir": "./dist",
"sourceMap": true,
"inlineSources": true,
"skipLibCheck": true
},
"exclude": [
"node_modules",
"dist",
"demo",
"config",
"coverage",
"src/**/*.spec.ts"
],
"angularCompilerOptions": {
"strictMetadataEmit": true,
"skipTemplateCodegen": true,
"trace": true
}
}
EUREKA
Fixed by playing with the tsconfig in both the library, and the angular project :
tsconfig.lib.json
{
"extends": "../../tsconfig.json",
"compilerOptions": {
// 👍 these two lines
"target": "es2015",
"module": "esnext",
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"enableResourceInlining": true
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}
and in the target project :
tsconfig.json
{
"compilerOptions": {
"module": "esnext"
}
}
tsconfig.app.json
{
"compilerOptions": {
"module": "esnext"
}
}