How to shim a dependency in babel.config.js in react-native? - react-native

I've got a dependency I'd like to shim on my react-native project. I currently have the following code on my babel.config.js file:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
],
};
};
I've found the extension babel-plugin-module-resolver which seems to be helpful (any other alternative would work too) and tried to follow their examples but they didn't work
I've tried the following:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
root: ["./src"],
alias: {
'#dependency/to-shim': 'path/to-shimmer',
},
},
],
],
};
};
but that doesn't work

I've got the same error.
The code when running works correctly.
The problem is with build. The path still absolute.
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['.'],
alias: {
'#services': './src/services',
},
},
],
'react-native-reanimated/plugin',
],
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#services*": ["./src/services"]
},
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"esModuleInterop": true,
"importsNotUsedAsValues": "error",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": ["esnext"],
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitUseStrict": false,
"noStrictGenericChecks": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": false,
"target": "esnext"
},
"include": ["src"],
"exclude": [
"node_modules",
"commitlint.config.js",
"metro.config.js",
"jest.config.js",
"babel.config.js"
]
}
screenshot - should be relative after build

Related

How to remove eslint single quote rule in React Native default eslint config?

I have set a react-native project with the cli. It works, but I have a very anoying eslint error:
Strings must use singlequote.eslint(quotes)
I have tried to write this:
module.exports = {
root: true,
extends: "#react-native-community",
rules: {
avoidEscape: true,
allowTemplateLiterals: true,
},
};
I also tried to create my own config:
module.exports = {
globals: {
Atomics: "readonly",
SharedArrayBuffer: "readonly",
},
parser: "#typescript-eslint/parser",
extends: ["#react-native-community"],
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
plugins: ["react", "react-hooks"],
rules: {
avoidEscape: true,
allowTemplateLiterals: true,
},
settings: {
react: {
version: "detect",
},
},
"sort-imports": [
"error",
{
ignoreCase: false,
ignoreDeclarationSort: false,
ignoreMemberSort: false,
memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
},
],
};
Nothing works. How to remove this rule?
You can turn off any specific rule like so:
{
"rules": {
"quotes": "off"
}
}

TS2307: Cannot find module '#/components/helper/utils/SimpleUtil.vue' or its corresponding type declarations

I work on Nuxt.js (Vue.js) project that uses TypeScript in VSCode. When importing components I'd like to cut off long paths to them. For example:
Instead of:
<script lang="ts">
import SimpleUtil from '../../../components/helper/utils/SimpleUtil.vue'
I'd like to have:
<script lang="ts">
import SimpleUtil from '#/components/helper/utils/SimpleUtil.vue'
Or:
<script lang="ts">
import SimpleUtil from 'components/helper/utils/SimpleUtil.vue'
But, when I use:
<script lang="ts">
import SimpleUtil from '#/components/helper/utils/SimpleUtil.vue'
There's an error:
The tsconfig.json file looks as following:
{
"compilerOptions": {
"target": "ES2018",
"module": "ES6",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": "./src",
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"types": [
"#types/node",
"#nuxt/types"
],
"resolveJsonModule": true
},
"paths": {
"~/*": [
"src/*"
],
"#/*": [
"src/*"
]
},
"include": [
"src/**/*.ts",
"src/**/*.vue"
],
"exclude": [
"src/node_modules",
"./node_modules",
".nuxt",
"dist"
]
}
The nuxt.config.js file looks as following:
export default {
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: 'Licota',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: ['~/assets/css/main.sass'],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [],
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
// https://go.nuxtjs.dev/typescript
'#nuxt/typescript-build',
// https://go.nuxtjs.dev/stylelint
'#nuxtjs/stylelint-module',
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'bootstrap-vue/nuxt',
],
// Axios module configuration (https://go.nuxtjs.dev/config-axios)
axios: {},
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
extractCSS: true,
},
srcDir: 'src/',
vue: {
config: {
productionTip: false,
devtools: true
}
}
}
How can I fix this issue?
This is the way that I declare paths in my jsconfig.json and it works for me:
"compilerOptions": {
"paths": {
"~/*": ["./*"],
"#/*": ["./*"],
"~~/*": ["./*"],
"##/*": ["./*"]
}
},
For more information you can check Nuxt TypeScript

Can't create code coverage for VUE files with karma, webpack and typescript

I am trying to create code coverage for VUE files using typescript in karma and webpack.
I am using istanbul-instrumenter-loader as a post process after but keep getting.
Everything works okay for pure .ts files, but when incluiding vue files I get
build failed (from ./node_modules/istanbul-instrumenter-loader/dist/cjs.js):
TypeError: Cannot read property 'fileCoverage' of undefined
When debugging istanbul-instrumenter-loader I noticed that
ee.exit(path); is undefined because the VUE files are being instrumented 3 times, the first two work okay but the third one is the one that crashes.
this is my webpack config
module.exports = {
node: {
fs: 'empty'
},
mode: 'development',
devtool: 'inline-source-map',
stats: 'verbose',
resolve: {
alias: {
Home: path.resolve( __dirname ),
Client: path.resolve( __dirname, 'client/' ),
ClientUtils$: path.resolve( __dirname, 'client/utils/index.utils.client.ts' ),
Views: path.resolve( __dirname, 'client/views/' ),
Components: path.resolve( __dirname, 'client/components/' ),
Constants$: path.resolve( buildPath, 'shared/constants.js' )
},
extensions: [
'.scss',
'.js',
'.ts',
'.vue'
]
},
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader'
}
]
},
{
test: /\.ts?$/,
exclude: /node_modules/,
use: [
{
loader: 'cache-loader'
},
{
loader: 'thread-loader',
options: {
workers: Math.max(require('os').cpus().length - 1, 1)
}
},
{
loader: 'ts-loader',
options: {
transpileOnly: true,
happyPackMode: true,
appendTsSuffixTo: [/\.vue$/]
}
}
]
},
{
test: /\.js$/,
exclude: [/dist/, /node_modules/, /coverage_server/, /coverage_client/],
loader: 'babel-loader'
},
{
test: /\.ts$/,
include: [/client/],
exclude: [
/node_modules/,
/\.spec\.ts$/,
/server/
],
enforce: 'post',
loader: 'istanbul-instrumenter-loader',
options: {
esModules: true
}
},
{
test: /\.(s*)css$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
]
},
plugins: [
new VueLoaderPlugin()
};
and my karma.conf is
module.exports = function(config) {
let files = [];
if (config.grep) {
files.push({ pattern: config.grep, type: 'module' });
} else {
files.push('client/index.client.spec.ts');
}
config.set({
frameworks: ["mocha", "chai", "sinon"],
files,
preprocessors: {
'client/**/*spec.ts': ['webpack', 'sourcemap']
},
webpack: require('./webpack.test.js'),
reporters: ['spec', 'dots', 'html', 'coverage-istanbul'],
browsers: ['ChromeHeadless'],
coverageReporter: {
dir: './coverage_client',
includeAllSources: true,
reporters: [{ type: 'lcov', subdir: '.' }, { type: 'text' }]
},
coverageIstanbulReporter: {
reports: ['text', 'lcov' ],
dir: './coverage_client',
fixWebpackSourcePaths: true,
'report-config': {
html: { outdir: 'html' }
}
},
htmlReporter: {
outputDir: 'karma_client_html', // where to put the reports
templatePath: null, // set if you moved jasmine_template.html
focusOnFailures: true, // reports show failures on start
namedFiles: false, // name files instead of creating sub-directories
pageTitle: null, // page title for reports; browser info by default
urlFriendlyName: false, // simply replaces spaces with _ for files/dirs
reportName: 'report_summary_filename', // report summary filename; browser info by default
// experimental
preserveDescribeNesting: false, // folded suites stay folded
foldAll: false // reports start folded (only with preserveDescribeNesting)
}
});
};
and my tsconfig is
{
"compilerOptions": {
"incremental": true,
"outDir": "./build/",
"target": "es2018",
"module": "CommonJS",
"lib": ["es2018", "dom", "dom.iterable"],
"allowSyntheticDefaultImports": true,
"inlineSourceMap": true,
"sourceMap": false,
"noImplicitAny": false,
"strict": true,
"alwaysStrict": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"types": [ "node", "mocha", "chai" ],
"baseUrl": ".",
"paths": {
"type-graphql": ["./node_modules/type-graphql/dist/browser-shim.ts"],
"Client/*": ["./client/*"],
"ClientUtils": ["./client/utils/index.utils.client.js"],
"Views/*": ["./client/views/"],
"Components/*": ["./client/components/*"],
"Constants": ["./shared/constants.ts"]
}
},
"include": [
"./client/**/*.ts",
"./client/**/*.vue",
"./server/**/*.ts",
"./shared/**/*.ts"
],
"exclude": [
"**/*.spec.ts",
"node_modules"
],
"files": ["./vue-shims.d.ts"]
}

ResponsiveMode is undefined in Jest test using lib-common-js

I'm trying to write tests for my Office Fabric React, initially started using react-scripts-ts, now ejected since I ran into this issue, and I'm running into the following error when using the withResponsiveMode library:
TypeError: Cannot read property 'large' of undefined
13 | const initialState: IAppState = {
14 | isMenuVisible: true,
> 15 | responsiveMode: ResponsiveMode.large
| ^
16 | };
17 |
18 | // Actions
I'm using the moduleNameMapper setting listed here: https://github.com/OfficeDev/office-ui-fabric-react/wiki/Fabric-6-Release-Notes.
My jest config is below:
module.exports = {
collectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}"],
globals: {
"ts-jest": {
tsConfigFile: "C:\\repos\\provider-portal-ui\\tsconfig.test.json"
}
},
moduleFileExtensions: [
"web.ts",
"ts",
"web.tsx",
"tsx",
"web.js",
"js",
"web.jsx",
"jsx",
"json",
"node",
"mjs"
],
moduleNameMapper: {
"^react-native$": "react-native-web",
"office-ui-fabric-react/lib/": "office-ui-fabric-react/lib-commonjs/"
},
setupFiles: ["<rootDir>/config/polyfills.js"],
testEnvironment: "node",
testMatch: [
"<rootDir>/src/**/__tests__/**/*.(j|t)s?(x)",
"<rootDir>/src/**/?(*.)(spec|test).(j|t)s?(x)"
],
testURL: "http://localhost",
transform: {
"^.+\\.css$": "jest-css-modules",
"^.+\\.tsx?$": "ts-jest"
},
transformIgnorePatterns: [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|ts|tsx)$"
]
};
tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"outDir": "build/dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}
tsconfig.test.json:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
I'm guessing this is some sort of configuration issue, as this code works fine when not being tested.
Found the answer to this. It seems to be an issue with Typescript & ts-jest and enums.
https://github.com/kulshekhar/ts-jest/issues/281

Karma,Jasmine,JSPM, Babel base.preset error

I am trying to use Karma, Jasmine, JSPM, and Babel all together. It seems I am getting an error I am not sure how to trace:
12 04 2016 19:59:04.407:ERROR [preprocessor.babel]: [BABEL] /Users/allen/work/twentytwenty.qualboard/src/TwentyTwenty.QualBoard.Web/wwwroot/config.js: Unknown option: base.preset. Check out http://babeljs.io/docs/usage/options/ for more info
It barks about config.js and the option base.preset. I am not sure why thought I have done a complete project search for base.preset and cannot find its existence.
Karma Config:
module.exports = function(config) {
config.set({
autoWatch: false,
babelPreprocessor: {
options: {
preset: ['es2015'],
sourceMap: 'inline',
},
},
basePath: '',
browsers: [
'PhantomJS',
],
colors: true,
concurrency: Infinity,
coverageReporter: {
type: 'html',
dir: 'converage/',
},
exclude: [],
files: [],
frameworks: [
'jspm',
'jasmine',
],
jspm: {
config: './wwwroot/config.js',
packages: './wwwroot/jspm_packages',
loadFiles: [
'test/**/*.js',
],
serveFiles: [
'test/**/*.js',
],
},
logLevel: config.LOG_INFO,
plugins: [
'karma-babel-preprocessor',
'karma-coverage',
'karma-jasmine',
'karma-jspm',
'karma-phantomjs-launcher',
'karma-spec-reporter',
],
port: 9876,
preprocessors: {
'./wwwroot/config.js': ['babel'],
'./wwwroot/aurelia/**/*.js': ['babel'],
'./wwwroot/test/**/*.js': ['babel', 'coverage'],
},
proxies: {
'/wwwroot/': '/TwentyTwenty.Qualboard.Web/wwwroot/',
'/jspm_packages/': '/wwwroot/jspm_packages',
},
reporters: [
'coverage',
'spec',
],
singleRun: true,
specReporter: {
maxLogLines: 1,
suppressErrorSummary: true,
suppressFailed: false,
suppressPassed: false,
supressSkipped: false,
},
});
};
My BabelRc:
{
"presets": ["es2015"]
}
I am starting Karma in the terminal by doing:
karma start
What am I missing?
You have a typo, it is presets and not preset:
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline',
},
}