Transpile specific `node_modules` package with rollup and babel - babeljs

I'm using rollup and would like to babel transpile a single node_modules package to ES5 (more precisely: to work with IE11).
With the following set-up it transpiles some of the code — classes → functions for example — but it doesn't transpile const to var's:
rollup.config.js:
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import babel from '#rollup/plugin-babel';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'umd',
},
plugins: [
resolve(),
commonjs(),
babel({
babelHelpers: 'bundled',
exclude: 'node_modules\/(?!(roughjs)\/).*', // ← Here I try to ES5 transpile roughjs which lives in `node_modules/roughjs/bundled/rough.esm.js`
}),
],
};
.babelrc
{
"presets": [["#babel/env", { "modules": false }]]
}
package.json:
// ...
"browserslist": "> 0.5%, IE 11, not dead",
// ...
My question is: how do I successfully transpile a single or multiple node_modules packages (given above example, if of help)?

Related

How to add babel and polyfills to a RequireJs project?

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?

Unable to resolve module when using babel module resolver + eslint + index files in react application

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.

Jest Test Support for the experimental syntax 'jsx' isn't currently enabled

I am writing first tests for my app and just install Jest.
My test is pretty simple, so I don't think the error I am getting is coming from there.
import React from 'react';
import renderer from 'react-test-renderer';
import FancyInput from './FancyInput';
describe('FancyInput', () => {
it('should render correctly', () => {
expect(
renderer.create(
<FancyInput />
)
).toMatchSnapshot();
});
});
Error when run the test is Support for the experimental syntax 'jsx' isn't currently enabled
also
`Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.`
My webpack file has the following thing:
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
],
plugins: [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-optional-chaining"],
["#babel/plugin-syntax-jsx"],
]
}
}
},
also my package.json has all the plugins I believe are necessary
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/plugin-proposal-optional-chaining": "^7.11.0",
"#babel/plugin-syntax-jsx": "^7.10.4",
"#babel/preset-react": "^7.0.0",
what am I missing here ?

swiperjs es module build doesn't work in IE11 browser

I am using webpack with babel to transpile modules and after adding swiper npm package to the build, IE11 browser stopped working because dom7 dependency is not transpiled properly. This is pointed out on the swiper's get started page, however it is not clear what has to be done to fix the problem.
After couple days of research and multiple attempts, I've finally got it working.
Important thing to note is that you must use babel.config.js instead of .babelrc so that node_modules could be included into build.
The final configuration:
babel.config.js (relevant section only):
module.exports = {
"presets": [
["#babel/env", {
"targets": {
"ie": "11"
}
}],...
webpack.config.js (relevant section only):
test: /\.js$/,
exclude: /node_modules\/(?!(swiper|dom7)\/).*/,
rules: [
{
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
rootMode: 'upward'
}
}]
}
]
Here is the article which got me to the right direction (see comment from RyanGosden) - https://www.bountysource.com/issues/79144083-not-working-in-ie11
Hope that helps other people to save some time!
Update in 2022:
Previous answer was correct, but swiper 7 adds a new esm dependency named ssr-window. So it needs to be added as below:
webpack.config.js (relevant section only):
test: /\.js$/,
exclude: /node_modules\/(?!(swiper|dom7|ssr-window)\/).*/,
rules: [
{
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
rootMode: 'upward'
}
}]
}
]

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