Unable to resolve module when using babel module resolver + eslint + index files in react application - visual-studio-code

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;

There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

Related

ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.
Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons.
This is my configuration:
svelte.config.test.cjs
const preprocess = require('svelte-preprocess');
require('dotenv').config()
module.exports = {
preprocess: preprocess({
replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
{ return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
})
};
jest.config.cjs
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: './svelte.config.test.cjs'
}
],
"^.+\\.(js)$": "babel-jest",
'^.+\\.(ts)$': [require.resolve('jest-chain-transform'),
{ transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
]
},
testMatch: ["**/spec/**/*.js"],
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2020",
"lib": ["es2020", "DOM"],
"target": "es2019",
"importsNotUsedAsValues": "error",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"allowJs": true,
"checkJs": true,
"paths": {
"$/*": ["src/*"]
}
},
"include": [
"src/**/*.d.ts",
"src/**/*.js",
"src/**/*.ts",
"src/**/*.svelte",
"src/**/*.svelte-kit",
"./jest-setup.ts"
],
"exclude": ["node_modules"]
}
I have this information about an error in jest:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
^
SyntaxError: Unexpected token '<'
9 | import { createPopper } from '#popperjs/core';
10 | import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
| ^
I added to jest.config.test.cjs
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]
after moduleNameMapper but still it doesn't work.
Thanks for your help.
running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like
module.export = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }], '#babel/preset-typescript']
};
my jest.config.js
const config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
'^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(carbon-icons-svelte))',
'<rootDir>/node_modules/(?!(carbon-components-svelte))'
],
moduleFileExtensions: ['js', 'ts', 'svelte']
};
export default config;

VSCode and Webpack alias

I'm not using path-intellisense, only the built in VSCode plugins.
When using Webpacks alias feature, VScode is reporting..
Unable to resolve path to module <Name of Alias>
Webpack alias setup is like..
alias: {
components: './client/javascripts/components/',
.....
and a jsconfig.json is setup like...
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"components/*": [
"./client/javascripts/components/*"
],
Are there any other configs / steps necessary to fix this?
It can be the problem in your file of webpack
try with this
resolve:{
alias:{
components: path.resolve(__dirname,'client/javascripts/components/')
},
},

Webpack with Babel lazy load module using ES6 recommended Import() approach not working

I'm trying to do code splitting and lazy loading with webpack using the import() method
import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
I'm getting
'import' and 'export' may only appear at the top level
Note top level imports are working fine, i'm just getting an issue when I try and using the dynamic variant of import()
var path = require('path');
module.exports = {
entry: {
main: "./src/app/app.module.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name]-application.js"
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
]
},
resolve : {
modules : [
'node_modules',
'bower_components'
]
},
devtool : "source-map"
}
EDIT:
If I change it so the syntax reads, it works.... but the chunk comments don't work to label the bundle. I'm confused because the documentation says the the following is depreciated.
The use of System.import in webpack did not fit the proposed spec, so
it was deprecated in webpack 2.1.0-beta.28 in favor of import().
System.import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
You need the plugin syntax-dynamic-import to be able to use the import() function with Babel.
Install it with:
npm install --save-dev #babel/plugin-syntax-dynamic-import
And add it to your plugins:
{
presets: ['es2015'],
plugins: ['#babel/plugin-syntax-dynamic-import']
}

Webpack 2 resolve alias

I have a little problem regarding resolving aliases in webpack 2. No matter what i do i cant resolve this. Here is the relevant code:
/* webpack.mix.js */
mix.webpackConfig({
module: {
rules: [
{
test: /\.js$/,
loader: 'eslint-loader'
}
]
},
resolve: {
root: path.resolve(__dirname),
// path is reqired at the beggining of file
alias: {
config: 'src/assets/js/config', // this is a config folder
js: 'src/assets/js'
}
}
});
/* router.js */
import { DashboardRoute } from 'config/route-components'
// this import is unresolved
The resolve.root option no longer exists in webpack 2. Instead it is merged into resolve.modules (from the official Migration Guide). Webpack even throws an error that it's not a valid property. If you want to be able to import from your root directory you would change the resolve config to:
resolve: {
alias: {
config: 'src/assets/js/config',
js: 'src/assets/js'
},
modules: [
path.resolve(__dirname),
'node_modules'
]
}
Alternatively you can use an absolute path in your resolve.alias like so:
resolve: {
alias: {
config: path.resolve(__dirname, 'src/assets/js/config'),
js: path.resolve(__dirname, 'src/assets/js')
}
}
Try this:
resolve: {
root: [
'node_modules',
path.resolve('src') // Resolve on root first
],
alias: {
config: 'src/assets/js/config', // this is a config folder
js: 'src/assets/js'
}
}
In ionic 3 (version 3.13.3), in order to get alias mapping working, you will have to define path mapping both in webpack.config.js & tsconfig.json
Please refer complete answer here question here