Babel module resolver not working with react-native - javascript

My babel module resolver is not working with React-Native (neither does intellij in VScode)
Here, Is my babel config
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
And jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#assets": ["./assets"],
"#modules": ["./modules"],
"#config": ["./config"],
"#utils": ["./utils"]
}
}
}
I changed import for one of my files and this is the error I get when I executed the build command from Xcode
Error: Error loading assets JSON from Metro. Ensure you've followed
all expo-updates installation steps correctly. Unable to resolve
module ../../modules/store/components/Filters from
src/utils/Router.js:
None of these files exist:
Where I imported the file like this
import Filters from '#modules/store/components/Filters';

I had the same problem, I just removed the '#' from my aliases and it seems working fine now.
Here is my babel.config.js
module.exports = function (api) { ■ File is a CommonJS module; it may be converted to an ES6 module.
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
require.resolve("babel-plugin-module-resolver"),
{
root: ["./src/"],
alias: {
// define aliases to shorten the import paths
components: "./src/components",
containers: "./src/containers",
contexts: "./src/contexts",
interfaces: "./src/interfaces",
organizer: "./src/screens/organizer",
screens: "./src/screens",
},
extensions: [".js", ".jsx", ".tsx", ".ios.js", ".android.js"],
},
],
],
};
};

Try resetting the cache, if above suggested answers don't work
react-native start --reset-cache
This worked for me. For more info see here

Change your module-resolver's root to ['./src/']:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src/'], // <-- here ✅
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};

Related

rollup-plugin-babel not recognizing JSX

I am having issues with RollupJS API. For some reason, its not recognizing JSX syntax. Rollup (API) is giving me this error.
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
2: import App from "./App";
3: const MyApp = (props) => {
4: return <View index={<App />} url={props.url} serverOptions={props.serverOptions}/>;
^
5: };
6: export default MyApp;
Here's the Rollup config.
export const loadBuildConfigurationOptions = (tsconfigOptions: object, root: Path = Process.Cwd()): RollupOptions => {
return <RollupOptions> {
input: Path.FromSegments(root, "src", "index.ts").toString(),
output: [
{
dir: Path.FromSegments(root, "dist").toString(),
format: "cjs"
}
],
external: [
"solid-js",
"solid-js/web",
"solidus"
],
plugins: [
typescript(tsconfigOptions),
nodeResolve({
preferBuiltins: true,
exportConditions: ["solid"],
extensions: [".js", ".jsx", ".ts", ".tsx"]
}),
nodePolyfill(),
babel({
babelHelpers: "bundled",
presets: [["solid", { generate: "ssr", hydratable: true }]],
}),
json(),
styles(),
copy({
targets: [
{ src: 'src/assets/**/*', dest: 'dist/src/assets' }
]
}),
],
preserveEntrySignatures: false,
treeshake: true,
};
}
I am using this in a build tool for a SolidJS SSR library I am developing. what is happening here is this function generates the appropriate Rollup configuration file to for the project being build by the user of this library. The returned Rollup configuration object is then being used by the Rollup JS API to build the actual application. Do I need to change the parameters in the babel plugin or something?
Okay. I figured it out. It’s quite silly really. I just had to make one change to the Babel plugin.
babel({
babelHelpers: "bundled",
presets: [["solid", { generate: "ssr", hydratable: true }]],
extensions: [“.js”, “.ts”, “.jsx”, “.tsx”],
}),
Adding the extensions option seemed to have fixed everything.

Eslint doesn't respect jsconfig paths

I have my express.js project in monorepo. I want to add custom path alias to it.
The directory structure is:
./
server/
----> jsconfig.json
----> .eslintrc.js
----> src/
--------> index.js
--------> modules/auth
-------------> auth.controller.js
jsconfig.json
{
"compilerOptions": {
"module": "ES6",
"baseUrl": "./",
"paths": {
"#modules/*": [
"src/modules/*"
]
}
},
"exclude": ["node_modules"]
}
.eslintrc.js
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {
'no-console': 'error',
'no-debugger': 'error',
},
settings: {
'import/resolver': {
alias: {
map: [
['#modules/*', 'src/modules/*'],
],
extensions: ['.js', '.json'],
},
},
},
};
Simply, I just tried to import auth controller in my index.js file.
import authRoutes from '#modules/auth/auth.routes';
but I get the following error: Unable to resolve path to module '#modules/auth/auth.controller' .eslint import/no-unresolved
please, don't suggest to turn off the rule.
I've alreadyy tried eslint-import-resolver-jsconfig, but I got Cannot resolve jsConfig, SyntaxError } on 150.
Because I used monorepo, there was a problem for ESLint or even lint-staged.
So now I have only one project per repository and:
Added custom paths in jsconfig.json:
"paths": {
"#modules/*": [
"./src/modules/*"
]
}
Installed eslint-import-resolver-jsconfig and added the following configuration to the eslint.json:
"extends": [
"airbnb-base",
"eslint:recommended"
],
"plugins": ["import"],
"settings": {
"import/resolver": {
"jsconfig": {
"config": "jsconfig.json"
}
}
}
Installed the Babel plugin babel-plugin-module-resolver and added the following settings to the .babelrc:
"plugins": [
[
"module-resolver",
{
"alias": {
"#modules": "./src/modules"
}
}
]
]
But, again: This only works if you have one project per repository and all your configuration files (.*rc, package.json, etc) are in the root level.
To achieve the above I use the module-alias package.
After installing it as a normal dependency, npm i --save module-alias, add the following to your package.json:
"_moduleAliases": {
"#modules": "./src/modules"
}
That will basically define the mappings for all the aliases you want to define.
To make it work, you will now need to import the following on top of your application under index.js:
require("module-alias/register"); // If using commonJS
// or
import "module-alias/register"; // If transpiling es6
You are now all set and should be able to import your files with absolute paths looking as:
const authRoutes = require("#modules/auth/auth.routes")
// or
import authRoutes from "#modules/auth/auth.routes";
In case eslint still flags the unresolved path, you may need to update your jsconfig.json or tsconfig.json to contain the below:
"paths": {
"#modules/*": ["src/modules/*"]
}
You can find the package documentation and read more about its usage here.

Rollup is not generating typescript sourcemap

I am using rollup with svelte + typescript + scss. My problem is that I am not able to generate source maps.
Following is my rollup config file:
import svelte from 'rollup-plugin-svelte'
import resolve from '#rollup/plugin-node-resolve'
import commonjs from '#rollup/plugin-commonjs'
import livereload from 'rollup-plugin-livereload'
import { terser } from 'rollup-plugin-terser'
import typescript from '#rollup/plugin-typescript'
import alias from '#rollup/plugin-alias'
const production = !process.env.ROLLUP_WATCH
const path = require('path').resolve(__dirname, 'src')
const svelteOptions = require('./svelte.config')
function serve() {
let server
function toExit() {
if (server) server.kill(0)
}
return {
writeBundle() {
if (server) return
server = require('child_process').spawn(
'yarn',
['run', 'start', '--', '--dev'],
{
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
}
)
process.on('SIGTERM', toExit)
process.on('exit', toExit)
},
}
}
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
alias({
entries: [
{ find: '#app', replacement: `${path}` },
{ find: '#components', replacement: `${path}/components` },
{ find: '#includes', replacement: `${path}/includes` },
{ find: '#styles', replacement: `${path}/styles` },
{ find: '#pages', replacement: `${path}/pages` },
],
}),
svelte(svelteOptions),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte'],
}),
commonjs(),
typescript({ sourceMap: !production }),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
}
I am not sure what exactly am I doing wrong. Here is the link to code I am using.
Any help will be deeply appreciated!
This is what worked for me: you need to set sourceMap: false in the typescript rollup plugin options.
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
...
},
plugins: [
...
svelte(...),
typescript({ sourceMap: false }),
...
]
}
It turns out rollup's sourcemap collapser conflicts with the typescript's plugin sourcemap generator. That's why it works on prod builds but not in dev builds (because originally it is sourceMap: !production). Just let rollup do the heavy lifting.
As also mentioned by others, it seems like the combination of TypeScript and Rollup leads to the problem. Disabling the source map in TypeScript only fixes the problem of mapping Svelte to TypeScript. However you only receive a source map showing source in the compiled JavaScript, not in the original TypeScript. I finally found a solution, that worked for me: Just add the Option inlineSources: true to the TypeScript options:
typescript({ sourceMap: !production, inlineSources: !production }),
This circumvents the problem by simply not creating a duplicate SourceMap, but by copying the source code from TypeScript into the SourceMap.
For anyone using terser, not svelte, this solved the same problem for me:
import sourcemaps from 'rollup-plugin-sourcemaps';
import { terser } from 'rollup-plugin-terser';
import typescript from '#rollup/plugin-typescript';
export default [
{
input: 'dist/index.js',
output: [
{
file: 'dist/cjs/index.js',
format: 'cjs'
},
{
file: 'dist/fesm2015/index.js',
format: 'es'
}
],
plugins: [
sourcemaps(),
terser(),
typescript({ sourceMap: true, inlineSources: true })
]
}
];
Apparently rollup-plugin-sourcemaps is needed to do the magic necessary to utilize the map files generated by the TypeScript compiler and feed them to terser.
For me, I am able to map, by making sourcemap: "inline"
In the /build/index.esm.js file will have mapping inside.
export default {
input: "src/index.ts",
output: [
{
file: 'build/index.esm.js',
format: 'es',
sourcemap: "inline"
},
],
plugins: [
typescript({ sourceMap: false, inlineSources: true }),
]
}
I was having a similar issue with Karma, rollup, and typescript. I fixed it by adding "sourceRoot":"/base/" to my tsconfig.json file.
Before: map file entries pointed to /src/.
After: map file entries pointed to /base/src/ and everything worked.
// tsconfig.rollup.json
"compilerOptions": {
"module": "ES2022",
"esModuleInterop": true,
"target": "ES2022",
"moduleResolution": "classic",
"sourceMap": true,
"sourceRoot": "/base/"
...
}
// rollup.config.js
import typescript from '#rollup/plugin-typescript';
export default [
{
input: './src/test/test_context.spec.ts',
output: {
file: './dist/test/test_context.spec.js',
format: 'es',
sourcemap: 'inline'
},
plugins: [
typescript({
tsconfig: './tsconfig.rollup.json'
})
]
}
];

How to include and use DefinePlugin in webpack config?

Hi there i am trying to use the define plugin so i can update the version number to make sure my JS refreshes after releasing a new build. I can't seem to get DefinePlugin to work properly though. I see it in the folder webpack and i'm trying to follow the documentation but i get errors that it isn't found. Here is my config:
const path = require('path'),
settings = require('./settings');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
'scrollerbundled': [settings.themeLocation + "js/scroller.js"],
'mapbundled': [settings.themeLocation + "js/shopmap.js"],
'sculptor': [settings.themeLocation + "js/sculptor.js"]
},
output: {
path: path.resolve(__dirname, settings.themeLocation + "js-dist"),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
],
plugins: [new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify('5fa3b9'),
})]
},
optimization: {
minimizer: [new UglifyJsPlugin({
uglifyOptions: {
mangle: true,
output: {
comments: false
}
}
})]
},
mode: 'production'
}
{
"parser": "babel-eslint",
"extends": [
"airbnb",
"plugin:react/recommended",
"prettier",
"prettier/react"
],
"plugins": ["react", "import", "prettier"],
"env": {
"browser": true
},
"settings": {
"import/resolver": {
"webpack": {
"config": "webpack.dev.js"
}
}
}
}
That's my eslintrc. This is for use absolute imports created in your webpack config with the modules alias. You need to install eslint-import-resolver-webpack
I Have "webpack": "^4.28.4" and define in webpack config
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
});
if you console that variables, you don't find it. I use in conditional
if (PRODUCTION) {
//do stuff
}
Another case is to set globals variables in a object and share with webpack.
here is an example
new webpack.ProvidePlugin({
CONFIG: path.resolve(__dirname, './CONSTS.js')
}),
// the path is src/CONST.JS
In the eslintrc file you can add that variables to avoid import errors.
"settings": {
"import/resolver": {
"webpack": {
"config": "webpack.dev.js"
}
}
}
then in any file you can use import {value} from 'CONFIG'
If you are using laravel mix, you can place that new webpack.DefinePlugin code into the plugins array of your .webpackConfig block:
webpack.mix.js:
mix
.webpackConfig({
devtool: 'source-map',
resolve: {
alias: {
'sass': path.resolve('resources/sass'),
}
},
plugins: [
new webpack.ProvidePlugin({
'window.Quill': 'quill', // <--------------------- this right here
__VERSION__: JSON.stringify('12345')
})
]
})
.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.copy([
'resources/fonts/*',
], 'public/fonts');
By extrapolation, that means you can also add this code to the similar block in your regular (not laravel mix) webpack config.
Install devtools globally
npm install -g #vue/devtools
... and try again.
If уоu have any issues try following the official instructions.

eslint error showing with webpack alias

In my webpack config. I defined aliases
alias: {
components: 'src/components/',
config: 'src/config/'
}
When I import a module from this path an eslint error occurred.
import ShadowWrapper from 'components/ShadowWrapper'
error 'components' should be listed in the project's dependencies. Run 'npm i -S components' to add it import/no-extraneous-dependencies
Thanks, Pranav for the solution to this issue!
I add some code to this post to make it more practical for others.
First of all, in webpack config file I had defined this alias:
alias:{
components: path.resolve(__dirname, "src", "components")
}
That allow me to import components in my app in that way:
import NewsFeed from 'components/NewsFeed'
I have installed eslint-import-resolver-webpack plugin and put below code into .eslintrc.js or .eslintrc file :
settings: {
'import/resolver': {
alias: {
map: [
['components', './src/components']
]
}
}
That's it after running linter I got rid of Unable to resolve path to module 'components/NewsFeed' error message
Hope it will be helpful for some of you!
Here is what worked for me:
I installed eslint-import-resolver-alias as dev dependency:
npm install eslint-plugin-import eslint-import-resolver-alias --save-dev
In the Webpack config (in my case, it was Vue config, which is merged with Webpack config by Vue-cli), I added a few aliases:
resolve: {
extensions: ['.js', '.vue', '.json', '.less'],
alias: {
Site: path.resolve(__dirname, 'src/site'),
Admin: path.resolve(__dirname, 'src/admin'),
Common: path.resolve(__dirname, 'src/common'),
Assets: path.resolve(__dirname, 'src/common/assets'),
Configs: path.resolve(__dirname, 'src/common/configs'),
Style: path.resolve(__dirname, 'src/common/style')
}
}
In the .eslintsrc (or .eslintsrc.js, if you use that), I added the plugin and maps for these aliases, as follows:
"extends": ["plugin:import/recommended"],
"settings": {
"import/resolver": {
"alias": {
"map": [
["Site", "./src/site"],
["Admin", "./src/admin"],
["Common", "./src/common"],
["Assets", "./src/common/assets"],
["Configs", "./src/common/configs"],
["Style", "./src/common/style"]
]
},
"extensions": [".js", ".less", ".json", ".vue"]
}
}
I have added extensions for clarity and some good measures, which you can choose to not use for yourself.
Optional:
If you use VS Code and want these aliases working with the path intellisense, add a file jsconfig.json at the root, and specify your alias paths:
{
"compilerOptions": {
"target": "esnext",
"allowSyntheticDefaultImports": false,
"baseUrl": "./",
"paths": {
"~/*": ["src/*"],
"Root/*": ["src/*"],
"Site/*": ["src/site/*"],
"Admin/*": ["src/admin/*"],
"Common/*": ["src/common/*"],
"Assets/*": ["src/common/assets/*"],
"Configs/*": ["src/common/configs/*"],
"Style/*": ["src/common/style/*"]
}
},
"exclude": ["node_modules", "dist"]
}
There are additional settings for React and Typescript. Check the documentation at official site.
This issue can be resolved by using the eslint-import-resolver-webpack
Another way, without mapping aliases between webpack.config.js and .eslintrc.
You can use eslint-import-resolver-webpack and setup you .eslintrc file like this:
{
"extends": [
"plugin:import/recommended"
],
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"moduleDirectory": [
"node_modules",
"src"
]
}
}
}
}

Categories