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!
Related
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.
(I couldn't think of a good title for this question, so feel free to edit it if you have a better idea)
My question
When I try to run tests for a specific component, I get this error:
Target container is not a DOM element.
I already found an answer to that in this SO question, but what I want to understand is:
Why does this happens in Typescript but not in Javascript?
Is this related to how Typescript imports modules?
My code
For this question purpose, I am removing unnecessary code.
index.tsx
import ReactDOM from 'react-dom'
import App from './app'
// This fooFunction needs to be declared here (project requirements)
export const fooFunction = (): string => 'foo'
ReactDOM.render(
<App />,
document.getElementById("root")
);
My component
import React from 'react'
import { fooFunction } from './index.js'
const MyComponent = () => {
const result = fooFunction()
return {
<p>{result}</p>
}
}
Now, when I write a test to my component, (I think) because my component is importing fooFunction from index.ts, index.ts is compiled and since "root" does not exist in my test world (jsdom), the line document.getElementById("root") fails and throws the error above.
However, I tried to reproduce the same thing in my Javascript project and it works fine. Any ideas why this is happening?
Update with additional files
Jest config (in package.json):
"moduleNameMapper": {
"\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(jpg|jpeg|png|svg)$": "<rootDir>/__mocks__/fileMock.js",
"^#App/(.*)$": "<rootDir>/src/$1",
"^lib/(.*)$": "<rootDir>/common/$1",
"^test/(.*)$": "<rootDir>/src/test/$1",
"^utils/(.*)$": "<rootDir>/src/utils/$1"
},
"transform": {
"^.+\\.(js|jsx|ts|tsx)?$": "babel-jest"
},
babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
'#babel/preset-env',
'#babel/preset-typescript',
'#babel/react',
[
'#babel/preset-react',
{
'runtime': 'automatic'
},
'preset-react-setting'
]]
const plugins = ['#babel/plugin-proposal-class-properties', '#babel/plugin-transform-runtime']
return {
presets,
plugins
}
}
tsconfig.json:
{
"compilerOptions": {
"baseUrl": "src",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": false,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"noImplicitAny": false,
"jsx": "react-jsx",
"sourceMap": true,
"declaration": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"incremental": true,
"noFallthroughCasesInSwitch": true,
"downlevelIteration": true
},
"include": [
"src/**/*",
"scripts"
],
"exclude": [
"node_modules",
"build",
"**/*.spec.ts"
]
}
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 tried to setup a new project with webpack, react, typescript. But I am unable to get it working.
I have tried html loader and tried various tutorials to solve the issue.
Webpack config:
const path = require("path");
module.exports = {
entry: {
app: ["./src/app"]
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
use: [
{
loader: "ts-loader",
options: {
transpileOnly: true,
compilerOptions: {
module: "es2015",
allowJs: true
}
}
}
],
include: [path.resolve(path.resolve(__dirname, "../"), "./src")]
}
]
},
resolve: {
extensions: [".js", ".jsx", ".ts", ".tsx"]
}
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"moduleResolution": "node",
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false,
"jsx": "react",
"allowJs": true,
"noImplicitThis": true,
"removeComments": false,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"lib": ["dom", "es5", "scripthost", "es2015", "es2017"],
"downlevelIteration": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"outDir": "./dist/"
}
}
app.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
ReactDOM.render(<></>, document.getElementById("root"));
But while compiling with : webpack --mode production :- throws error :
ERROR in ./src/app.tsx 4:16
Module parse failed: Unexpected token (4:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import * as ReactDOM from "react-dom";
| //import { Home } from "./pages/home";
ReactDOM.render(<>, document.getElementById("root"));
|
# multi ./src/app app[0]
i tried it and this include is the problem. include: [path.resolve(path.resolve(__dirname), "./src")]... no need to go back from dirname and it will work .
Credits: #JurajKocan
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"
}
}