I have followed this document and set an absolute path across the project. But when I run test case it gives me following error
Your application tried to access assets, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.
Required package: assets (via "assets\icons")
Required by: E:\Project\src\components\LayoutContainer\
Require stack:
src/components/LayoutContainer/index.jsx
src/components/LayoutContainer/__test__/index.spec.js
27286 | enumerable: false
27287 | };
> 27288 | return Object.defineProperties(new Error(message), {
| ^
27289 | code: { ...propertySpec,
27290 | value: code
27291 | },
at internalTools_makeError (.pnp.js:27288:34)
at resolveToUnqualified (.pnp.js:28247:23)
at resolveRequest (.pnp.js:28345:29)
at Object.resolveRequest (.pnp.js:28423:26)
My Package.json for jest configuration is as follow
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!src/components/**/*.{js,jsx}",
"!<rootDir>/node_modules/",
"!<rootDir>/path/to/dir/",
"!src/**/*.css",
"!src/setUpTests.js",
"!src/index.jsx"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
},
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
},
I tried to follow many open solutions. But none are working for me
My jsonconfig.json file
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
I added the following configuration as part of craco file and worked for me
module.exports = {
jest: {
configure: {
moduleNameMapper: {
// Jest module mapper which will detect our absolute imports.
'^assets(.*)$': '<rootDir>/src/assets$1',
'^pages(.*)$': '<rootDir>/src/pages$1',
'^config(.*)$': '<rootDir>/src/config$1',
'^navigation(.*)$': '<rootDir>/src/navigation$1',
'^utils(.*)$': '<rootDir>/src/utils$1',
'^components(.*)$': '<rootDir>/src/components$1',
'^services(.*)$': '<rootDir>/src/services$1',
// Another example for using a wildcard character
'^~(.*)$': '<rootDir>/src$1'
}
}
}
}
reference - https://resir014.xyz/posts/2019/03/13/using-typescript-absolute-paths-in-cra-20
Related
I am not really strong with setting up my custom npm packages, therefore I am asking for help. I am trying to test my custom ESLint plugin rules on another project. For this, I have set up two projects in one root directory and linked them, using the file linking option (find the image of the file structure attached):
"eslint-plugin-winniepukki-guidelines": "file:../guide"
.eslintrc configuration file on the project, where I want to use my custom ESLint plugin:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'winniepukki-guidelines',
],
rules: {
'winniepukki-guidelines/use-license': 'error',
'winniepukki-guidelines/avoid-names': 'error',
},
};
Unfortunately, the rules do not apply properly with the following error:
Definition for rule 'winniepukki-guidelines/avoid-names' was not found.eslint(winniepukki-guidelines/avoid-names). This is how the avoid-names.js file looks like:
module.exports = {
meta: {
messages: {
avoidName: "Avoid using variables named '{{ name }}'"
}
},
create(context) {
return {
Identifier(node) {
if (node.name === "foo") {
context.report({
node,
messageId: "avoidName",
data: {
name: "foo",
}
});
}
}
};
}
};
And this is the ESLint package's index.js file itself, illustrating how do I export them:
const path = require('path');
const requireIndex = require('requireindex');
module.exports.rules = requireIndex(path.join(__dirname, 'rules'));
Project overview: https://i.stack.imgur.com/hLKcH.png
I am encountering very weird behavior of babel path transpilation. in my project some modules are called as following
import module from '~modulename'
where ~ means import given 'modulename' from root of project directory. now how this works fine for dev (babel-node for running project). but when i run babel src -d lib on my project for transpiling es6 js everything is converted (trans piled) but this path doesn't so in build i am always left with require('~modulename') instead require('../../...modulename').
Solutions i have tried
aliasing ~ to ./ in babel.config.js through module-resolver-plugin
Babel.config.js
module.exports = __babel => {
// Use cache.
__babel.cache(true)
// Return configuration.
return {
'presets': [
[
'#babel/preset-env',
{
'modules': false
}
]
],
'plugins': [
'#babel/plugin-proposal-throw-expressions',
'#babel/plugin-proposal-export-default-from',
'dynamic-import-node',
'babel-plugin-root-import',
['babel-plugin-module-resolver', { 'alias': { '~': './' } }]
['module-resolver', { 'root': ['./', 'packages/*'] }],
['#babel/plugin-transform-modules-commonjs', { 'allowTopLevelThis': true }],
['#babel/plugin-transform-runtime', { 'regenerator': true }]
],
'env': {
'production': {
'presets': ['minify'],
'plugins': [
'transform-remove-console',
'minify-dead-code-elimination'
]
}
}
}
}
While I am aware that Babel is capable of transpiling TypeScript itself, I've had enough weird issues I'd like to first transpile TypeScript->JS and then run Babel on that.
I've got my tsconfig.json files working as expected. When I compile my TypeScript (from ./src folder relative to babel.config.json's path), it outputs to a ./build folder. I have Babel set to take what's in the ./build folder and output to the ./dist folder.
The output of TSC shows import {bar} from 'foo' and import {thing} from 'foo/util', as expected. But Babel's output looks like ../../../libfoo/libfoo.js when it should be ../../libfoo/libfoo.js
No matter what I try with root/cwd, I can't seem to get that extra ../ to disappear. I've managed to make it go away a couple times, but then I rebuild without changing the babel config, and it comes back.
My babel.config.json currently looks like this:
{
"presets": [
["#babel/preset-env", {"targets": {
"node": true,
"electron": "80"
}}],
["#babel/preset-typescript", { "onlyRemoveTypeImports": true }]
],
"plugins": [
["babel-plugin-module-resolver", {
"alias": {
"^foo/(.+)": "./libfoo/\\1.js",
"^foo$": "./libfoo/libfoo.js"
}
}],
["#babel/plugin-transform-modules-umd"],
["#babel/plugin-transform-typescript", {
"allowNamespaces": true,
"allowDeclareFields": true,
"onlyRemoveTypeImports": true
}],
["#babel/plugin-proposal-pipeline-operator", { "proposal": "fsharp" }],
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-do-expressions",
"#babel/plugin-proposal-logical-assignment-operators",
"#babel/plugin-proposal-partial-application",
["#babel/plugin-proposal-decorators", { "decoratorsBeforeExport": true }],
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-bind"
],
"sourceMaps": true
}
Well, I found a solution that doesn't really fix the problem but makes it works.
My files structure is something like this:
|-dist
|-src
|-db
|-connect
|-index.ts
|-index.ts
|-.babelrc
When babel compiles the code, the import of db/connect in src/index.ts, go from this:
import ... from "db/connect"
to this:
var _connect = require("../db/connect");
To resolve this, I simply add /dist to the paths in .babelrc
before:
[
"module-resolver",
{
"root": ["./"], # or ["src"] or "src" or ["./src"] or "./src" or any way you can imagine
"alias": {
"db": "./db",
}
}
}
]
after:
[
"module-resolver",
{
"alias": {
"db": "./dist/db",
}
}
}
]
And the import is now:
var _connect = require("../dist/db/connect");
As you said, the root doesn't affect the require path, so I just removed it.
This doesn't fix the problem, but makes it work.
Hope it helps, good luck! :)
I'm using Next.js for Server Side Rendering of React application (with styled-components) and have issue with Babel plugins I'm using to show name of the components I'm using in code.
This is my .babelrc file:
{
"env": {
"development": {
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
},
"production": {
"presets": "next/babel",
"plugins": [
[
"babel-plugin-styled-components",
{
"displayName": false,
"ssr": true
}
]
]
},
"test": {
"presets": [
[
"env",
{
"modules": "commonjs"
}
],
"next/babel"
]
}
}
}
When I'm running cross-env NODE_ENV=development concurrently "tsc --watch" next
I'm getting these lines - meaning .babelrc is used during copilation:
[1] > Using external babel configuration
[1] > Location: "...../.babelrc"
[1] > Using "webpack" config function defined in next.config.js.
But once I go to dev tools and see some styled-component I can see this: class="sc-iyvyFf gGaJAt" but on my code I have this definition:
const Title = styled.div`
font-size: 40px;
line-height: 1.13;
`
As it seems from documentation example - I should get something like ... <button class="Button-asdf123 asdf123" /> instead of just <button class="asdf123" />. But I don't.
After going deeper I found this issue ( https://github.com/styled-components/styled-components/issues/1103#issuecomment-324302997 ) based on errors I get in browser console that said:
It seems that only the server code is being transpiled and not the client code 😉
So Question: How to test if babel works correctly and .babelrc is being used in all places?
P.S. In my case those classes that I've got on client side had this prefix sc- meaning in my head styled-components. So I was not sure if the plugin from .babelrc works at all or it works, but I haven't set any special property in declaration of styled-components thus get this general prefix sc-
UPDATE Here is my custom next.conf.js I'm using
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const { ANALYZE } = process.env
const path = require('path')
module.exports = {
exportPathMap: function() {
return {
'/': { page: '/' }
}
},
webpack: function(config) {
if (ANALYZE) {
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'server',
analyzerPort: 8888,
openAnalyzer: true
})
)
}
config.resolve.alias = {
'styled-components': path.resolve('./node_modules/styled-components/')
}
return config
}
}
Looks like no one has unfortunately answered this before;
What you're seeing probably comes down to this little piece of code you posted: tsc --watch
If you execute TypeScript transpilation before Babel and leave it up to TypeScript to transpile to ES5, it'll transpile all tagged template literals, not giving our plugin anything to hook onto.
Since you're already using next.js you won't need to set up your Babel pipeline from scratch. Rather you only need to disable this type of transpilation in TypeScript.
I'd suggest you to set target inside your tsconfig.json to ESNext so that it leaves everything up to Babel.
https://www.typescriptlang.org/docs/handbook/compiler-options.html (See "--target")
I try to test my react-native application using AVA and the babel-preset-react-native
My config looks like this:
"scripts": {
"test": "ava"
},
"ava": {
"files": [
"src/**/__tests__/*.js"
],
"failFast": true,
"require": [
"react-native-mock/mock.js",
"babel-register"
],
"babel": {
"presets": [
"react-native"
]
}
},
"devDependencies": {
"ava": "^0.13.0",
"babel-preset-react-native": "^1.2.4",
"babel-register": "~6.4.3",
"react-native-mock": "0.0.6"
}
…and fails like this:
/Users/zoon/Projets/xxxxx/node_modules/babel-register/node_modules/babel-core/lib/transformation/file/index.js:556
throw err;
^
SyntaxError: /Users/zoon/Projets/xxxxx/src/reducers/env.js: Unexpected token (12:8)
10 | case types.RECEIVE_CHANGE_ENV:
11 | return {
> 12 | ...state,
| ^
13 | current: Environments[action.env]
14 | };
15 | default:
If I export this babel config in a .babelrc file and use "babel": "inherit" in my AVA config, it fails in an other way:
/Users/zoon/Projets/xxxxx/node_modules/lodash-es/lodash.js:10
export { default as add } from './add';
^^^^^^
SyntaxError: Unexpected token export
I can't understand how to correctly configure this. I've tried Mocha, encountered the same problems.
babel-register ignores node_modules by default. You can set ignore:false in your .babelrc to disable that behavior. You could (probably should) also specify a more limited regular expression to avoid processing everything in node_modules.
See the docs: https://babeljs.io/docs/usage/require/
Your complete config should probably look something like this:
.babelrc
{
"presets": ["react-native"],
"ignore": false
}
package.json
{
"ava": {
"babel": "inherit"
}
}