How to add babel and polyfills to a RequireJs project? - babeljs

I am working on a legacy project which uses RequireJs to load and resolve all the dependencies. It works fine on modern browsers, but i need to add support for IE11.
I tried to use babel 7 with #babel/preset-env with following .babelrc
{
"presets": [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3,
"targets": {
"browsers" : ["ie>=11"]
},
"modules": false
}]
],
"compact": false
}
the import statements injected by the preset as following
import "core-js/modules/es.function.name.js";
cause error "import statements can't be used outside a module". Even when I use modules: "amd", then core-js is imported as
define(["core-js/modules/es.array.filter.js", "core-js/modules/es.object.to-string.js", "core-js/modules/es.string.includes.js", "core-js/modules/es.function.name.js", "core-js/modules/es.regexp.exec.js", "core-js/modules/es.string.split.js", "core-js/modules/es.string.small.js", "core-js/modules/es.string.search.js"], function (_esArrayFilter, _esObjectToString, _esStringIncludes, _esFunctionName, _esRegexpExec, _esStringSplit, _esStringSmall, _esStringSearch) {
"use strict";
//...
});
which throws error like "define is not defined in require.js".
When using useBuiltIns: "entry", and then including core-js as
require(["core-js", ../other modules], function(corejs, ...){
}
)
in the main.js file, it fails to correctly resolve the path of the files even though I have included the path to core-js in require.config.paths.
I tried #babel/runtime and #babel/plugin-transform-runtime but no luck there.
So my question is what would be the best way to add babel and the required polyfills in my RequireJs project so that it is compatible with IE 11?

Related

How to pass options to babel plugin transform-modules-commonjs?

I create a Vue 2 project by Vue-Cli 5, then I want to remove "use strick" in the complied code.
As I Know, the #babel/plugin-transform-strick-mode may be enabled via #babel/plugin-transform-modules-commonjs, and the plugin is included in #babel/preset-env under the modules option.
But the Vue-Cli used a preset #vue/babel-preset-app by a plugin #vue/cli-plugin-babel for babel.
So my question is How pass strictMode: false as an option to the transform-modules-commonjs by #vue/babel-preset-app which preset is in the #vue/cli-plugin-babel ?
module.exports = {
presets: [["#vue/cli-plugin-babel/preset", { modules: "auto" }]],
plugins: [
// I tried this way, but it throw many errors like:
/**
ERROR in ./node_modules/axios/dist/node/axios.cjs 11:15-32
Module not found: Error: Can't resolve 'stream' in 'D:\workspace\cqset_offical_website\node_modules\axios\dist\node'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
*/
["#babel/plugin-transform-modules-commonjs", {}],
[
"component",
{
libraryName: "element-ui",
styleLibraryName: "theme-chalk",
},
],
],
};

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

vscode Prettier not working after update vscode v1.53

I have been using vscode prettier for few months now. I always used it to auto format my codes with vscode shortcut Shift + Alt + F or type >Format Document in command palette
But all of a sudden, vscode gave me this error this error msg: "invalid prettier configuration file detected. See log for details.". This happend after update vscode to v1.53
When I click on "show Log". It show me this:. (It is much much more longer of cause, but I think here is the most import part)
["ERROR" - 2:50:11 PM] Invalid prettier configuration file detected.
["ERROR" - 2:50:11 PM] Must use import to load ES Module: /home/koonfoon/git-repos/koonfoon/someRepo/.prettierrc.js
require() of ES modules is not supported.
require() of /home/koonfoon/git-repos/koonfoon/someRepo/.prettierrc.js from /home/koonfoon/.vscode-server/extensions/esbenp.prettier-vscode-5.9.1/node_modules/prettier/third-party.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename .prettierrc.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/koonfoon/git-repos/koonfoon/someRepo/package.json.
Inside my package.json has value "type": "module".
This is how my .prettierrc.js looks like:
// .prettierrc.js
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 120,
tabWidth: 4
};
.eslintrc.js:
// .eslintrc.js
module.exports = {
"env": {
"commonjs": true,
"es2021": true,
"node": true
},
"extends": [
//"eslint:recommended",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
}
};
Please note: it was working fine until vscode updated to v1.53
My repo is written in typescript.
I have no ideal what cause this error.
Please help.
Thank you.

Babel polyfill includes all polyfills no matter which targets are set

I am using Babel 7.1 together with rollup (v0.67). This is my rollup config:
{
input: 'src/svg.js',
output: {
file: 'dist/myBundle.js',
name: 'myBundle',
sourceMap: true,
format: 'iife'
},
plugins: [
resolve({browser: true}),
commonjs(),
babel({
include: 'src/**',
runtimeHelpers: true,
babelrc: false,
presets: [["#babel/preset-env", {
modules: false,
targets: {
firefox: "63"
},
useBuiltIns: "usage"
}]],
plugins: [["#babel/plugin-transform-runtime", {
corejs: false,
helpers: true,
regenerator: true,
useESModules: true
}]]
})
]
}
I want to polyfill older browsers. According to the docs, I need to include babel-polyfill in my entry point which I did. Now babel should include only the polyfills needed (because of useBuiltIns: "usage"). However, even when specifying the newest Browsers as target, I get the full load of code into my bundle (10000 lines of code).
What I tried:
I tried useBuiltIns: "entry" which fixes it for newer browsers but its not what I want (it just includes all polyfills which are potentially needed by the browser no matter if they are actually used in the code).
change the order of the rollup plugins
not include the babel-polyfill import
I have no idea why this is happening. It would be great if someone could solve this issue. Its driving me crazy!
And if someone knows as a bonus why no sourcemap is generated I dont mind getting an answer for that, too
Hey I made a repo which explores a good babel/rollup setup utilising preset-env and useBuiltIns 'usage'.
// Rollup plugins
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
export default {
input : 'main.js',
output : {
file : 'app.js',
format : 'iife',
name : 'PROJECT'
},
plugins : [
resolve(),
babel({
exclude : 'node_modules/**',
presets : [[
'#babel/env', {
useBuiltIns : 'usage'
}
]],
plugins : [
'#babel/plugin-transform-runtime'
],
runtimeHelpers : true
}),
commonjs()
]
};
Take a look https://github.com/matt3224/rollup-babel7
If you can figure out how to reduce the output further submit a PR

Is there a way to use loose modules when using es2015 preset in babel 6?

I tried to use following babelrcs:
{
"presets": [
["es2015", { "transform-es2015-modules-commonjs": { "loose": true } }]
]
}
fails with "Invalid options type for foreign"
{
"presets": ["es2015"],
"plugins": [
["transform-es2015-modules-commonjs", { "loose": true }]
]
}
ignores the "loose" option
{
"plugins": [
["transform-es2015-modules-commonjs", { "loose": true }]
]
}
does not use the preset
By enabling es2015, you are asking for non-loose-mode modules. If you want loose module modes in Babel v6 (at least at the moment), you would need to explicitly list the plugins you wish to use by listing everything that is part of es2015.
I ended up creating a preset es2015-mod for this same purpose - an exact copy of Babel's es2015 with loose modules enabled.
babel-preset-es2015-loose package has been deprecated. With babel-preset-es2015 v6.13.0+, you can now configure your .babelrc like so:
{ presets: [ ["es2015", {"loose": true}] ] }
For me it was an old babel-core version. You need at least 6.13+
NEW: Using es2015-loose preset
es2015-loose is a preset that uses modify-babel-preset to modify es2015 preset and enable loose mode where available.
Use it like that:
{
"presets": ["es2015-loose"]
}
Make sure to install both es2015 and es2015-loose packages:
$ npm install --save-dev babel-preset-es2015-loose babel-preset-es2015
PS: There are other loose presets for example if you target node versions >= 4 you can use es2015-node4-loose preset.