jsconfig.json path alias not working properly - reactjs

I have a react project created using create-react-app, and I'm trying to add material kit react to the project. I have placed the assets and components of material kit react under src/template and I would like to change the path of assets from src/assets to src/template/assets.
The problem is when I configured jsconfig.json to define the path for assets alias I get the error "Module not found" when using assets, but if I use the template alias it works just fine.
Here is my jsconfig.json file:
{
"compilerOptions": {
"baseUrl": "src",
"target": "es6",
"paths": {
"template/*": ["src/template/*"],
"assets/*": ["src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
If someone can help me to understand why the template alias is working and not the assets alias.

please try the code below.
I think your 'baseUrl' is wrong.
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"paths": {
"template/*": ["./src/template/*"],
"assets/*": ["./src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
So, This will make VS Code IntelliSense work.
But there may be other issues. (..Because I went through it.)
Other issue is that resolve does not work.
error is the same
This dependency was not found:
* template/somtething in ./blahblah..
To install it, you can run: npm install --save template/somtething`
If there is an error above,
try to set an alias to the 'template' folder using the following Webpack configuration.
https://webpack.js.org/configuration/resolve/

Related

StencilJS error with React output target - You may need an additional loader to handle the result of these loaders

I'm creating some basic elements in Stencil for a custom design system. I created some basic components, which work fine on their own as custom elements, but throw errors when used as React components.
I generated the React components via Stencil by includng the #stencil/react-output-target in stencil.config.ts.
reactOutputTarget({
componentCorePackage: '#sr-design-system/simple-stencil-demo',
proxiesFile: './react/src/components/index.ts',
includeImportCustomElements: true
}),
I then uploaded all of the components (custom elements & React) to a private npm package and installed them in a seperate project. The custom elements seem to work fine, but with the React elements I get the following error.
ERROR in ./node_modules/#sr-design-system/simple-stencil-demo/react/src/index.ts 6:12
Module parse failed: Unexpected token (6:12)
File was processed with these loaders:
* ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| import { createReactComponent } from './react-component-lib';
|
> import type { JSX } from '#sr-design-system/simple-stencil-demo/';
|
| import { defineCustomElement as defineSrText } from '#sr-design-system/simple-stencil-demo/dist/components/sr-text';
# ./src/App.jsx 7:0-73
# ./src/index.jsx 7:0-24 12:33-36
webpack 5.65.0 compiled with 1 error and 1 warning in 63 ms
I've been stuck on this issue for days now. Any idea what the solution could be?
===tsconfig.json===
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowUnreachableCode": false,
"declaration": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"lib": ["dom", "es2017"],
"module": "es2015",
"moduleResolution": "node",
"pretty": true,
"removeComments": false,
"strictPropertyInitialization": false,
"target": "es2017",
"baseUrl": ".",
"paths": {
"#srds/react": ["./react"]
},
"jsx": "react",
"jsxFactory": "h"
},
"include": ["src"]
}
===stencil.config.ts===
import { Config } from '#stencil/core';
import { reactOutputTarget } from '#stencil/react-output-target';
export const config: Config = {
namespace: 'simple-stencil-demo',
bundles: [{ components: ['sr-text'] }, { components: ['text-demo'] }],
outputTargets: [
reactOutputTarget({
componentCorePackage: '#sr-design-system/simple-stencil-demo',
proxiesFile: './react/src/components/index.ts',
includeImportCustomElements: true,
}),
{
type: 'dist',
esmLoaderPath: './loader',
},
{
type: 'dist-custom-elements',
},
{
type: 'docs-readme',
},
{
type: 'www',
serviceWorker: null, // disable service workers
},
],
buildEs5: 'prod',
};
I figured out what the issue. For some reason, the dist folder was not being generated for me every time I ran npm run build.
Sometimes it was generated, other times it wasn't. I believe it was due to some errors in my component code, which failed silently. So now I check for the dist folder every time I build the library.
In my final, working attempt I went with the monorepo approach as advised by the Stencil team in their documentation.
Here are all I took the steps for a basic Stencil library with a React output:
Create a monorepo
Create a Stencil Library
Generate components using npx stencil generate
Update name in package.json to MY_LIBRARY
npm i #stencil/react-output-target
Add the React Wrapper function to stencil.config.ts
react({
componentCorePackage: 'MY_LIBRARY',
proxiesFile: '../MY_REACT_LIBRARY/src/components/stencil-generated/index.ts',
includeDefineCustomElements: true,
}),
Move back to root level of monorepo
Create a React library
git clone https://github.com/ionic-team/stencil-ds-react-template react-components
Update name in package.json to MY_REACT_LIBRARY
Change private to false in package.json
In the Stencil Library
Run npm run build
Check if dist folder contains all subfolders (cjs, collection, components, esm, types, web-components, index.cjs.js, index.js)
Run npm link to generate a global symlink
In the React Library
Run npm link MY_LIBRARY
Run npm i
Run npm run build (Not sure if this step is required as it is not documented, but I did it anyway)
Run npm link
Move back to root level of monorepo
Create a React demo
npx create-react-app MY_REACT_DEMO --template typescript
npm link MY_REACT_LIBRARY
Import a component from the library and use it in App.tsx
npm run start
When I confirmed everything worked fine, I added a basic lerna.jsonconfig for npm package management. Using this config, Lerna will automatically handle symver for our packages.
{
"version": "independent",
"npmClient": "npm",
"command": {
"publish": {
"allowBranch": ["master", "react-generation"],
"ignoreChanges": ["*.md", "build.js", "config.json"],
"message": "(auto) Lerna publish",
"registry": "URL_TO_MY_PACKAGE_REGISTRY"
},
"bootstrap": {
"ignore": "component-*",
"npmClientArgs": ["--no-package-lock"]
}
},
"packages": ["MY_LIBRARY", "MY_REACT_LIBRARY"]
}
After configuring Lerna, I published using the command npx lerna publish, following their publishing wizard.
When it's published the package can be installed in any React project using npm i MY_REACT_LIBRARY and it should work.

Add absolute paths to app created by "Create React App"

I have created an app by Create React App and to be more specific I'm also using typescript.
I can't figerout how to set absolute paths to access to my components, pages, etc..
In a different scenario I would update my tscongig with something like:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#components/*": ["src/components/*"]
}
}
}
but I have no idea how to implement this as I'm using react-scripts
any idea?
Create a tsconfig.json file and add the code below.
{
"compilerOptions": {
"baseUrl": "src"
},
"include": [
"src"
]
}
Then you can import your components as
import Header from 'components/Header';
You should be able to use the same approach if create a jsconfig.json file in your solution, which supports the same baseUrl and rootPath properties as tsconfig.
Alternative is adding an .env file in your solution with the following line:
NODE_PATH=src/
Also, apart from the env file add this to your jsconfig.json
{
"rootDir": "src",
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": ["*"]
}
}
}
This should resolve both the compiler being able to find your absolute imports, and linter handling them properly.
See Building Your App / Importing a Component / Absolute Imports in the Create React App docs.
You can configure your application to support importing modules using absolute paths. This can be done by configuring a jsconfig.json or tsconfig.json file in the root of your project. If you're using TypeScript in your project, you will already have a tsconfig.json file.
Below is an example jsconfig.json file for a JavaScript project. You can create the file if it doesn't already exist:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
If you're using TypeScript, you can configure the baseUrl setting inside the compilerOptions of your project's tsconfig.json file.
Now that you've configured your project to support absolute imports, if you want to import a module located at src/components/Button.js, you can import the module like so:
import Button from 'components/Button';

Typescript (at-loader) compiler errors in WebPack

I am using Visual Studio 2017 to write an Angular SPA, but I use WebPack to run it. Currently I let VS build the Typescript into JS and WebPack uses that JS to create the build artefact.
I want to move to WebPack building the Typescript so its easier for our CI server to build the project. For some reason VS can compile the Typescript fine but awesome-typescript-loader cannot.
My Typescript is written using ES6 modules i.e.
import * as angular from "angular";
import * as moment from "moment";
import "angular-material";
import { ExpensesService } from "../../main/components/reports/expenses/expenses.service";
import { IJourney } from "../../Interface/IJourney";
I get these errors from WebPack / Awesome-Typescript-Loader when I compile run it. Note that all of these are in the node_modules folder and not my code (that I can tell?)
ERROR in [at-loader] ./node_modules/#types/node/index.d.ts:32:11
TS2451: Cannot redeclare block-scoped variable 'Error'.
ERROR in [at-loader]
./node_modules/#uirouter/angularjs/lib-esm/services.d.ts:9:9
TS2717: Subsequent property declarations must have the same type. Property 'stateProvider' must be of type 'StateProvider', but here has
type 'StateProvider'.
ERROR in [at-loader]
./node_modules/awesome-typescript-loader/lib/runtime.d.ts:20:13
TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type
'WebpackRequire'.
ERROR in [at-loader] ./node_modules/tsutils/src/typeguard.d.ts:140:70
TS2694: Namespace 'ts' has no exported member 'EnumLiteralType'.
ERROR in [at-loader] ./node_modules/uri-js/src/punycode.d.ts:9:17
TS2714: The expression of an export assignment must be an identifier or qualified name in an ambient context.
My tsconfig.json (which I force VS to use) is
{
"compileOnSave": true,
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"lib": [ "es2015" ],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"typings"
],
"include": [
"./src/**/*.ts",
"node_modules/**/*.d.ts",
"scripts/typings/d.ts"
],
"files": [
"./src/app/bootstrap.ts"
]
}
I won't copy packages.json here for brevity, but I include all appropriate npm packages i.e. #types/angular, #types/angular-material etc.
In my WebPack.config here is the relevant setup
module.rules = {
{
test: /\.ts$/,
exclude: /node_modules/,
use: ["awesome-typescript-loader"],
},
}
resolve: {
extensions: [".ts"],
modules: [node_modules"]
},
In my case, excluding in the tsconfig.json didn't work as it works for not implicit compiling, but still goes to the files if explicitly required, and exclude anyway work just to reduce include set.
Adding skipLibCheck to tsconfig.json solved the problem:
{
"compilerOptions": {
// ...
"skipLibCheck": true,
},
// ...
}
NOTE: This was using awesome-typescript-loader in webpack. With ts-loader i didn't have problem.
The cause of the error is you're compiling the definition files
To fix it
removing "node_modules/**/*.d.ts" and "scripts/typings/d.ts"
in tsconfig.json will resolve your problem.

How do I solve ParseError: 'import' and 'export' may appear only with 'sourceType: module' when importing UpgradeAdapter?

I am trying to upgrade an existing anguar.js app to angular 2, following https://angular.io/docs/ts/latest/guide/upgrade.html.
The app is already written with Typescript, and we are using browserify and tsify to compile and bundle the app.
After installing the angular 2 dependencies with npm, and trying to bootstrap the hybrid app, browserify gives me the following error:
/my-project/node_modules/#angular/upgrade/static.js:8
export { downgradeComponent } from './src/aot/downgrade_component';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
The error only shows up after adding the following code:
import {platformBrowserDynamic} from '#angular/platform-browser-dynamic';
import {AppModule} from './app.module';
import {UpgradeModule} from '#angular/upgrade/static';
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['sagaDesktopApp']);
});
This is my tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true
}
}
Any help would be very much appreciated.
I've reproduced the problem. It's related to the fact that there is a static.js file in #angular/upgrade and when Browserify attempts to resolve #angular/upgrade/static it resolves to:
node_modules/#angular/upgrade/static.js
However, the intention is for it to resolve to:
node_modules/#angular/upgrade/static/package.json
The package.json in the static directory contains a main entry that's used by non-ES6 bundlers like Browserify.
Browserify mimics Node's module resolution mechanism and it's supposed to check for the file before the directory, so to fix the problem, append a trailing slash to the import:
import { UpgradeModule } from '#angular/upgrade/static/';
Browserify will then check the directory first and will resolve the package.json to the bundle.
If you are interested, there is more information on the package.json file's main/module thing in this Tsify issue.

Use typings in vscode without reference path for each d.ts

I have TypeScript and Typings working in vs2015 with the Web Analyzer plugin. I've resolved all vs2015 errors. Now I am trying to set it up in vscode. I've setup a gulp task and vscode reports:
error TS2304: Cannot find name 'angular'
I can resolve it with the following line, but is there a simpler way than listing out each file individually? I.e., vs2015 compiles the TypeScript without issue and knows how to use the Typings files.
/// <reference path="../typings/browser/ambient/angular/index.d.ts" />
I started with gulp-tsc and also tried gulp-typescript, but both require this.
var tsc = require("gulp-tsc");
var typescript = require("gulp-typescript");
var $ = require("gulp-load-plugins")({ lazy: true });
gulp.task("ts-watcher", function() {
gulp.watch("./app/**/*.ts", ["ts-compile"]);
});
gulp.task("ts-compile", function() {
var tsProject = typescript.createProject('tsconfig.json');
return gulp.src(config.allts) //["./app/**/*.ts"]
.pipe(typescript(tsProject))
.pipe(gulp.dest("dest/"));
});
gulp.task("default", ["ts-watcher"]);
{
"compilerOptions": {
"module": "amd",
"rootDir": "src",
"sourceMap": true,
"target": "es5",
"removeComments": true,
"outFile": "./build/build.js"
},
"compileOnSave": true,
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts",
"packages"
]
}
My typings folder is in the same folder as tsconfig.json.
Restarting VSCode did not help.
This is similar to Including d.ts type definition files in VSCode, but I am 1) including more information, 2) using VSCode 1.1.0, and 3) I have a TSconfig, not a JSconfig. Would a jsconfig help?
Add a main.d.ts file in your app folder. (Or the src folder where all your ts file resides) with below content, (check the relative path based upon your project structure)
/// <reference path="../typings/main.d.ts" />
you might have to restart VS code.
Maybe you shouldn't exclude typings/main.d.ts as you seem to do. This file is the entry point that includes all registered type defs and hence also angular.
A tsconfig (or jsconfig) in your workspace root is required for vscode to automatically pick up type definitions from typings directory in your workspace root.
In the following example only browser .d.ts-files are used.
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"sourceMap": true
},
"exclude": [
"typings/main.d.ts",
"typings/main",
"node_modules"
]
}
To install additional typings you can use the following typings command
typings install --ambient jquery --save
or use one of the following vscode extensions:
typings-installer
typings-autoinstaller

Resources