Babel Path Transpilation to absolute Path - javascript

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

Related

Babel - how to set aliases to outside of the root directory?

I have a monorepo:
domain/
entities/
account.ts
...
mobile/
src/
app.ts
node_modules/
package.json
babel.config.js
I want to set an alias so that app.ts can simply call:
import { Account } from 'domain/entities/account'
instead of
import { Account } from '../../../domain/entities/account'
I tried doing it like so:
const path = require('path')
module.exports = (api) => {
api.cache(true)
return {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
['module:react-native-dotenv', {
moduleName: 'react-native-dotenv'
}],
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx'
],
alias: {
domain: path.resolve(__dirname, '../domain')
}
}
]
]
}
}
But it doesn't work, unfortunately.
It throws:
Error: Unable to resolve module /home/kibe/work/iros-customer-frontend/domain/entities/account from ...
None of these files exist:
* ../domain/entities/account(.js|.jsx|.ts|.tsx)
How can I import stuff from outside the main directory?
Go to "domain" Folder and add a new file package.json with following content
{
"name": "domain"
}
Now you import like this
import { Account } from 'domain/entities/account'

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.

NuxtJS with Babel 7: still have spread operator in built files

I'm desperately trying to make my NuxtJS app work with IE11. I implemented babel config in many ways to build a compatible version but I still have spread operators in built pages files, as if Babel didn't transform Nuxt code.
Here is my config:
nuxt.config.js
const pkg = require('./package')
const path = require('path');
module.exports = {
mode: 'universal',
// ...
build: {
babel: {
babelrc: true
},
extend(config, ctx) {
config.resolve.modules.push(path.resolve(__dirname, 'assets'));
const svgRule = config.module.rules.find(rule => rule.test.test('.svg'));
svgRule.test = /\.(png|jpe?g|gif|webp)$/;
config.module.rules.push({
test: /\.svg$/,
loader: 'vue-svg-loader',
}, {
test: /\.js$/,
loader: 'babel-loader'
})
}
}
}
.babelrc
{
"presets": [["#babel/preset-env", { "modules": false }]],
"plugins": [
"#babel/transform-runtime",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-spread",
"#babel/plugin-proposal-object-rest-spread"
],
"env": {
"test": {
"presets": [["#babel/preset-env", { "targets": { "node": "current" } }]]
}
}
}
.browserslistrc
# Browsers that we support
>0.2%
not dead
not ie < 11
not op_mini all
Despite that config, I still see some spread operators used in Nuxt built pages, like the following generated by nuxt:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["pages/events/_slug.pages/index"],{
/***/ "./assets/svg/events/market.svg":
/*!**************************************!*\
!*** ./assets/svg/events/market.svg ***!
\**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
functional: true,
render(_h, _vm) {
const { _c, _v, data, children = [] } = _vm;
const {
class: classNames,
staticClass,
style,
staticStyle,
attrs = {},
...rest
} = data;
I searched from some time across different issues about NuxtJS and Babel, but Nuxt claims that it works with IE9 without extra Babel configuration, which is not the case here. I'd like to understand why the code is not transpiled the right way.
I ran into a similar issue: A Nuxt app wouldn't work in the Edge browser because of spread operators in #nuxtjs/axios and bootstrap-vue. I did find a solution.
The build property in nuxt.config.js should be defined as follows:
build: {
babel: {
babelrc: true,
configFile: './babel.config.js'
},
transpile: [ '#nuxtjs/axios', 'bootstrap-vue' ],
// Other config
}
The transpile property is key here. Internally, Nuxt defines an exclude for babel-loader that ignores everything in node_modules, unless it's in transpile.
Using babel.config.js also appears to matter, and the official Babel documentation says you should use it if you want to process node_modules.
babel.config.js:
module.exports = function (api) {
api.cache(true);
return {
sourceType: 'unambiguous',
presets: ['#nuxt/babel-preset-app'],
plugins: ['#babel/plugin-proposal-object-rest-spread']
};
}
You don't need include or exclude here, as it's taken care of by Nuxt, as noted.

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

after phoenix 1.3 upgrade app.js are not loaded

I updated my phoenix 1.2 to 1.3 follwing the phoenix upgrade description.
Now assets/js/app.js can't be loaded:
Uncaught Error: Cannot find module 'js/app' from '/'
After debugging the problem, I found that the expected module is app not js/app.
When I change the module name in the brunch-config.js autoRequire modules to ["app"] instead of ["js/app"] it works. I don't understand what is the problem or what I did in my app, that the default settings don't work.
Here my assets/brunch-config.js
exports.config = {
// See http://brunch.io/#documentation for docs.
files: {
javascripts: {
joinTo: "js/app.js"
},
stylesheets: {
joinTo: "css/app.css",
order: {
after: ["../priv/static/css/app.css"] // concat app.css last
}
},
templates: {
joinTo: "js/app.js"
}
},
conventions: {
assets: /^(static)/
},
// Phoenix paths configuration
paths: {
// Dependencies and current project directories to watch
watched: ["static", "css", "js", "vendor"],
// Where to compile files to
public: "../priv/static"
},
// Configure your plugins
plugins: {
babel: {
// Do not use ES6 compiler in vendor code
ignore: [/vendor/]
},
copycat: {
"fonts": ["node_modules/font-awesome/fonts"] // copy node_modules/font-awesome/fonts/* to priv/static/fonts/
},
sass: {
options: {
includePaths: [
"node_modules/bootstrap-sass/assets/stylesheets",
"node_modules/font-awesome/scss"
], // tell sass-brunch where to look for files to #import
precision: 8 // minimum precision required by bootstrap-sass
}
}
//sass: {
// mode: "native" // This is the important part!
// },
},
modules: {
autoRequire: {
"js/app.js": ["js/app"]
}
},
npm: {
enabled: true,
globals: {
$: 'jquery',
jQuery: 'jquery'
}
}
};
And my assets/js/app.js is here:
import "phoenix_html"
import "./datetimepicker"
thanks for any help, tipps or ideas to understand/solve the problem.
The problem is related to the brunch version.
updating brunch to:
brunch#2.10.10
solved the problem.

Categories

Resources