babel-plugin-module-resolver adding extra ../ to path - javascript

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! :)

Related

Broken path when building electron app with webpack and electron-forge

I have an electron app where I use webpack and build with electron-forge (I think the problem comes from one of these two).
The issue appears when I build the app with electron-forge, no problem during the development process. When the app is built and I start it, no images are displayed and the debugging tool show me that the path it is trying to access is a wrong path.
I build like this:
"main": "./.webpack/main",
"scripts": {
"make": "electron-forge make"
}
When the software is compiled path like this: resources/app/.webpack/renderer/login/images/logo.png
But the image is located here: resources/app/.webpack/renderer/images/logo.png
The login folder wrongly added to the path is there because in my package.json I have this configuration for electron-forge:
"plugins": [
[
"#electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/front/views/window.html",
"js": "./src/front/scripts/login.ts",
"name": "login",
"preload": {
"js": "./src/preload.ts"
}
},
// other entrypoints
]
}
}
]
]
And we can see that the name of one entrypoint is "login" which is the first page of my app and which is the page the image is supposed to be on. But in development no login folder is created however when I build, login is added to the path of image that are supposed to be on the login page.
I have tried to install electron-webpack and do some changes to the webpack config files. For now, in the file webpack.renderer.config.js I have this:
const rules = require('./webpack.rules');
// other rules
rules.push({
test: /\.(png|svg|jpg|gif)$/,
include: [
path.resolve(__dirname, "src/front/images"),
],
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
});
module.export = {
module: {
rules
}
// other things
}

Babel Path Transpilation to absolute Path

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'
]
}
}
}
}

Jest : TypeError: require(...) is not a function

The application is written by React with ES6 so import and export statements are used inside the application. So Jest is configured to work compatible with ES6, but compiled node_modules dependencies are causing an error which is
TypeError: require(...) is not a function
when tests started.
I assume this is happening because Jest configured to work with babel-jest to handle import statements, but compiled codes are using require for handling the modules. I tried to exclude node_modules folder, but nothing changed. I think, ES6 modules using compiled modules placed into the node_modules as a dependency because of that it cannot be excluded? Is it possible?
Also, I am having a problem to understand how does jest handle both import and require at the same time? If ES6 codes are compiled first then each module will be handled as require after that compiling process. So what is the problem?
Here are the configurations
jest.config.js
module.exports = {
clearMocks: true,
moduleNameMapper: {
"^.+\\.(js|jsx)$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/mocks/fileMock.js",
"\\.(css|scss|sass|less)$":
"<rootDir>/mocks/styleMock.js"
},
modulePathIgnorePatterns: [
"node_modules/"
]
};
babel.config.js
/* eslint-disable */
module.exports = {
presets: [
"#babel/preset-react",
[
"#babel/preset-env",
{
targets: {
browsers: ["ie >= 9", "safari >= 8"]
}
}
]
],
plugins: [
["#babel/plugin-proposal-decorators", { legacy: true }],
[
"#babel/plugin-proposal-class-properties",
{ loose: true }
],
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-object-assign",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
],
env:{
test:{
plugins: [
["#babel/plugin-proposal-decorators", { legacy: true }],
[
"#babel/plugin-proposal-class-properties",
{ loose: true }
],
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-object-assign",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
}
};
If you are tying to import any file for example a font file, then simply create a mockFile that just have
// mockFile.ts or mockFile.js
export default {};
and then in jest.config.js
moduleNameMapper: {
'^.+\\.(woff2)$': '<rootDir>/<path to file>/mockFile.ts',
},
This will resolve to the mockFil when it will try to import a font file. You can also add other file extentions like '^.+\\.(jpg|png|woff2)$: '<rootDir>/<path to file>/mockFile.ts'.
It should work.

babel with express js :avoid relative path imports

Currently my imports like this
import router from '../../app/routes'
Is there any way to avoid this ../../ for eg: import router from 'app/routes' in typescript I can do it like
{
"#app/*":["app/*"]
}
Is anything same available in Babel??
Yes, you can use babel-plugin-module-resolver
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"app": "./app",
},
}]
]
for instance to alias all references to "app" to be ./src/app.

how to test if babel works and my plugins are executed

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")

Categories

Resources