how to use commonjs rollup and babel together - babeljs

I have found several question about this problem.
The best relate to my problem is this
I cannot understand how to right configure my app.
I must use commonjs and target to Node 10 syntax.
I have an example file:
example.js
const Html = require('./Html');
Html.js
/**
* Modulo Html
* #module Html
*/
// Routes will be rendered into children
/*
* This module give an function with fixed title and id
* for root element
*
* #param {Object} param0
* #param {string} param0.title
* #param {string} [param0.idRoot='root']
* #returns {function({childern: JSX.Element}):JSX.Element}
*/
module.exports = function Html({ title, idRoot='root' }) {
return (
/*
*
* #param {Object} param0
* #param {JSX.Element} param0.children
* #returns {JSX.Element}
*/
function ({children}) {
return (
<html>
<head>
<title>{title}</title>
</head>
<body>
<div id="{idRoot}">{children}</div>
</body>
</html>
);
}
);
};
my .babelrc is:
{
"plugins": [
[
"babel-plugin-inferno"
, {
"imports": true
}
]
]
}
my rollup.config.js is:
import resolve from '#rollup/plugin-node-resolve';
import babel from '#rollup/plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
let commonPlugins = [
, babel({
plugins: [
'#babel/plugin-external-helpers'
]
, extensions: [
".jsx"
, ".js"
]
, exclude: "node_module/**"
, babelHelpers: "external"
, presets: [
[
'#babel/preset-react'
]
, [
'#babel/preset-env'
, {
loose: true
, modules: false
, targets: {
browsers: '> 1%, IE 11, not op_mini all, not dead'
, node: 10
}
}
]
]
})
, resolve({
main: true
, extensions: [
'.jsx'
, '.js'
, '.mjs'
, '.json'
, '.node'
]
, preferBuiltins: false
})
, commonjs({
include: [
'src/**/*.js'
, 'src/**/*.jsx'
]
, ignoreGlobal: true
, transformMixedEsModules: true
})
];
let commonExtenal = [
'inferno'
, 'inferno-server'
, 'inferno-router'
, 'fastify'
, 'fastify-plugin'
, 'assert'
]
export default [
{
input: 'src/index.jsx'
, output: {
file: 'dist/bundle.js',
format: 'cjs'
}
, plugins: commonPlugins
, external: commonExtenal
}
, {
input: 'src/example.js'
, output: {
file: 'dist/example.js'
, format: 'cjs'
, exports: 'default'
}
, plugins: commonPlugins
, external: commonExtenal
}
]
I have try all order combination for 2 week but allways I get this example.js in dist folder:
'use strict';
var require$$0 = ...
var inferno = require('inferno');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
/**
* Modulo Html
* #module Html
*/
// Routes will be rendered into children
/*
* This module give an function with fixed title and id
* for root element
*
* #param {Object} param0
* #param {string} param0.title
* #param {string} [param0.idRoot='root']
* #returns {function({childern: JSX.Element}):JSX.Element}
*/
module.exports = function Html(_ref) {
var title = _ref.title,
_ref$idRoot = _ref.idRoot;
return (
/*
*
* #param {Object} param0
* #param {JSX.Element} param0.children
* #returns {JSX.Element}
*/
function (_ref2) {
var children = _ref2.children;
return inferno.createVNode(1, "html", null, [inferno.createVNode(1, "head", null, inferno.createVNode(1, "title", null, title, 0), 2), inferno.createVNode(1, "body", null, inferno.createVNode(1, "div", null, children, 0, {
"id": "{idRoot}"
}), 2)], 4);
}
);
};
var Html = /*#__PURE__*/Object.freeze({
__proto__: null
});
What is wrong: in example.js no export have to do and var Html = /*#__PURE__*/Object.freeze({ ... haven't to exist, the first function Html is right.
What is the right configuration to get plugin work well?
my package.json is:
{
"name": "...",
"version": "1.0.0",
"main": "index.js",
"engines": {
"node": ">=10"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prebublish": "npm run build",
"build": "rollup --config",
"start": "node ./dist/example.js"
},
"standard": {
"ignore": [
"*.jsx"
]
},
"targets": {
"node": "current"
},
"peerDependencies": {
"inferno": "^7.4.6",
"inferno-server": "^7.4.6",
"inferno-router": "^7.4.6"
},
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/plugin-external-helpers": "^7.12.1",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#babel/preset-env": "^7.12.1",
"#babel/preset-react": "^7.12.5",
"#rollup/plugin-babel": "^5.2.1",
"#rollup/plugin-buble": "^0.21.3",
"#rollup/plugin-commonjs": "^16.0.0",
"#rollup/plugin-node-resolve": "^10.0.0",
"babel-plugin-inferno": "^6.1.1",
"cross-env": "^7.0.2",
"inferno": "^7.4.6",
"inferno-router": "^7.4.6",
"inferno-server": "^7.4.6",
"jsdoc": "^3.6.6",
"rollup": "^2.33.1",
"rollup-plugin-terser": "^7.0.2",
"standard": "^16.0.0",
"tap": "^14.10.8"
}
}
help!
best regards,
Leonardo

The solution was avoid to use #rollup/plugin-commonjs:
I do not know if this plugin is buggy or if I am not be able to use it in the right manner.
Not using the plugin bring me to move all import export in ES6 module syntax to be understend by rollup.
by now using gulp, rollup, #rollup/plugin-babel only on jsx file, babel-plugin-inferno, #rollup/plugin-node-resolve I can compile an example using fastify, inferno, hyperscript or JSX syntax together.
this is my gulpfile.js (this have to be in commonjs):
const { series } = require('gulp');
const del = require('del');
const rollup = require('rollup');
const fs = require('fs')
const { nodeResolve } = require('#rollup/plugin-node-resolve');
const { babel } = require('#rollup/plugin-babel');
let commonPlugins = [
, nodeResolve({
main: true
, extensions: [
'.jsx'
, '.js'
, '.mjs'
, '.json'
, '.node'
]
, preferBuiltins: false
})
, babel({
babelrc: true
, plugins: [
'#babel/plugin-external-helpers'
]
, extensions: [
".jsx"
]
, exclude: "node_module/**"
, babelHelpers: "external"
, presets: [
[
'#babel/preset-react'
]
, [
'#babel/preset-env'
, {
loose: true
, modules: 'auto'
, debug: false
, targets: {
browsers: '> 1%, IE 11, not op_mini all, not dead'
, node: 10
}
}
]
]
})
];
let commonExtenal = [
'inferno'
, 'inferno-server'
, 'inferno-router'
, 'fastify'
, 'fastify-plugin'
, 'assert'
, 'hyperscript'
, 'inferno-hyperscript'
, 'hyperscript-helpers'
]
const clean = function(cb) {
const deleted = del.sync(['dist/**', '!dist'], {force: true});
console.log('Deleted paths:\n', deleted.join('\n'));
cb();
}
async function buildPlugin() {
const bundle = await rollup.rollup({
input: 'src/index.js'
, plugins: commonPlugins
, external: commonExtenal
});
return bundle.write({
output: {
file: 'dist/bundle.js'
, format: 'cjs'
, exports: 'default'
}
});
}
async function buildExample() {
const bundle = await rollup.rollup({
input: 'src/example.js'
, plugins: commonPlugins
, external: commonExtenal
});
return bundle.write({
output: {
file: 'dist/example.js'
, format: 'cjs'
// , exports: 'default'
}
});
}
exports.build = series(clean, buildPlugin, buildExample);
all work fine.
best regards,
Leonardo

Related

Babelrc configuration for IE11 support

I am trying to configure .babelrc for my react project but, cant make it work in IE11.
Can someone take a look at my configuration and see if there are things that I am missing, please?
[.babelrc]
{
"presets": [
"#babel/preset-env",
[
"#babel/preset-react",
{
"useBuiltIns": "usage",
"corejs": 3.26
}
]
],
"plugins": ["#babel/plugin-transform-runtime"]
}
[webpack.common.config.js]
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
// Default. Can be erased for code simplification
entry: "./src/index.js",
output: {
filename: "[name].[contenthash].js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /[\\/]node_modules[\\/]/,
use: {
loader: "babel-loader",
},
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.html"),
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
],
};
I have tried a lot of things(workarounds), but nothing seems to work.
The order of presets, importing core-js at the top of index.js file...

How to tree-shake Lodash and Mui imports in Storybook 5

I'm using Mui and Lodash in my CRA project with Storybook 5.
I successfully tree-shake both Mui and Lodash imports using babel-plugin-import in CRA, using the following .bablerc.js
module.exports = {
presets: ["react-app", "#babel/preset-typescript"],
plugins: [
[
"babel-plugin-import",
{
libraryName: "#material-ui/core",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"core",
],
[
"babel-plugin-import",
{
libraryName: "#material-ui/icons",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"icons",
],
["lodash"],
],
};
However I am unable to do the same in Storybook 5. When I try using the same config in Storybook (copying over to .storybook/.babelrc.js), the babel config gets loaded, but results in no improvement in Storybook load times (Mui icons still seem to be loading for about a minute). Removing the presets
from babel config doesn't help either.
Storybook is hosted in the same root directory as my CRA, sharing node_modules.
How can I get the import tree-shaking to work in Storybook 5?
Here are my configs:
// .storybook/presets.js
module.exports = ['#storybook/preset-create-react-app'];
// .storybook/webpack.config.js
module.exports = function({ config }) {
// https://github.com/storybookjs/storybook/issues/6974#issuecomment-499903328
config.module.rules.unshift({
test: /\.stories.js$|\.stories.jsx$|\.stories.tsx$|\.stories.ts$/,
loaders: [require.resolve('#storybook/source-loader')],
enforce: 'pre',
});
return config;
};
// .storybook/.babelrc.js
module.exports = {
presets: ["react-app", "#babel/preset-typescript"],
plugins: [
[
"babel-plugin-import",
{
libraryName: "#material-ui/core",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"core",
],
[
"babel-plugin-import",
{
libraryName: "#material-ui/icons",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"icons",
],
["lodash"],
],
};
// .storybook/config.js
iimport { addDecorator, addParameters, configure } from "#storybook/react";
import { withKnobs } from "#storybook/addon-knobs";
import { withConsole } from "#storybook/addon-console";
import { INITIAL_VIEWPORTS } from "#storybook/addon-viewport";
import "../src/config";
import withIntl from "./decorators/intl";
import withReduxStoreAndConnectedRouter from "./decorators/reduxStoreWithDependentProviders";
import stylesProvider from "./decorators/stylesProvider";
import setup from "./decorators/setup";
const req = require.context("../src", true, /stories.tsx$|stories.ts$/);
const loadStories = () => req.keys().forEach((filename) => req(filename));
addDecorator(setup);
addDecorator(stylesProvider);
addDecorator(withKnobs);
addDecorator(withIntl);
addDecorator(withReduxStoreAndConnectedRouter);
addDecorator((storyFn, context) =>
withConsole(consoleConfig)(storyFn)(context)
);
addParameters({
viewport: {
viewports: INITIAL_VIEWPORTS,
},
});
addParameters({
backgrounds: [
{ name: "darkGray", value: "#34373c" },
{ name: "gray", value: "#A0A0A0" },
{ name: "lightGray", value: "#F0F0F0" },
],
});
configure(loadStories, module);

How to make rollup expand `require` statements?

I'm trying to wrap my head around rollup.
I'm using a library that generates a file with this format: IIFE with a require statement. For example
// index.js
(function() {
const myThing = require('./thing');
})()
//thing.js
module.exports = { a: 3 };
I'm trying to use rollup with a bunch of other things, but my bundle.js ends up looking like this:
(function () {
var myThing = require('./thing');
})();
What do I need to do so that my bundle.js ends up looking like this?:
(function () {
var myThing = { a: 3 };
})();
In case there is a problem with my setup, here is the rollup.config.js that I'm using:
var babel = require('rollup-plugin-babel');
export default {
input: 'index.js',
output: {
file: 'dist/bundle.js',
format: 'es'
},
plugins: [
babel({
exclude: 'node_modules/**'
})
]
};
These are the packages I have installed:
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.6.1",
"rollup": "^0.58.2",
"rollup-plugin-babel": "^3.0.4"
And my babel config:
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}
To build, I'm just calling rollup -c.
Okay, I figured it out. All I had to use was use the CommonJS plugin:
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
resolve(),
commonjs(),
babel({
exclude: 'node_modules/**'
})
]
};

Karma debugging in Chrome no longer working

We are working on an Angular project where we are using Karma/Jasmine for our testing environment. We've been using the karma-chrome-launcher for debugging the tests and it was working great. For some reason, it has stopped working lately. I can't figure out why though, as we haven't changed anything regarding that pipeline. We tried updating to latest Karma (1.4.1), but that didn't help. Has anyone else seen this issue and been able to fix it? Help is appreciated. I've attached two images of what the Chrome inspector looks like when you first open the debugger and then after setting a breakpoint and hitting Refresh (it should look the same as the 1st image, but doesn't) edit: karma.config at bottom as well
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js')
])
.concat(pathSrcHtml)
.concat('karmaMobileFramework/*.js');
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: false,
autoWatch: true,
preprocessors : {
'/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'directive-templates'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'jasmine-matchers', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-jasmine-matchers',
'karma-ng-html2js-preprocessor',
'karma-htmlfile-reporter',
'karma-junit-reporter'
],
coverageReporter: {
type : 'html',
dir : 'reports/coverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: 'report-jenkins' }
]
},
reporters: ['progress', 'html', 'junit'],
junitReporter: {
outputDir: 'reports/tests/',
outputFile: 'test-results.xml',
useBrowserName: false
},
htmlReporter: {
outputFile: 'reports/tests/results.html',
pageTitle: 'BOLT Unit Tests'
},
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
config.set(configuration);
};

Can't set breakpoint in Chrome with Babel and Webpack

I have started a new project using the "new" stack: React+Webpack+Babel.
I am trying to explore of this work, and I am facing an issue with debugging in chrome. I can't set breakpoints on some lines in source files when I use Babel and Webpack. (I create sourcemaps).
I would like to be able to debug JSX files.
I have set a little project to reproduce the problem.
https://github.com/pierre-hilt/babel_webpack_sourcemap.git
Here is my configuration:
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
babelrc:
{
"presets": [
"es2015",
"react"
],
"plugins": []
}
App.jsx (I try to break on line 6 but it is impossible...)
import React, { Component, PropTypes } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
};
}
changeTitle(newTitle) {
this.setState({ title: newTitle });
}
render() {
return (
<div>
This is {this.state.title}
</div>
);
}
}
App.propTypes = { title: PropTypes.string };
export default App;
I tried different devtool options (cheap, module, ...).
I also tried Babel loader, but is does not work either.
Do you have any idea? Is it a known issue?
OK, I found a workaround that works fine!
babelrc
{
"presets": [
"react"
],
"plugins": []
}
Babel script
"babel": "babel client -d build --source-maps",
webpack config
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
],
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
I first transpile JSX with babel only, then I transpile ES2015 with babel loader and webpack.
At the end I got source files where I can set break points anywhere!