Babel not transpiling - babeljs

I'm using babel from gulp to attempt to create React code.
When I run babel either from gulp or just from the commandline, the output of my code is exactly the same as the input. Nothing is changed.
This is my babel.config.js
const presets = [
[
"#babel-env",
{
targets : {
edge : "17",
ie : "8",
firefox : "60",
chrome : "67",
safari : "11.1"
},
useBuiltIns: "usage"
}
],
]
This is the contents of the file I want to transform:
import React from 'react' ;
import ReactDOM from 'react-dom';
console.log("starting...");
const foo = "foo" ;
const bar = "bar"
const testFn = (foo, bar) => {
console.log("in testFn");
}
This is my task definition:
gulp.task('scripts', function() {
return gulp.src(['./src/js/main.js' ])
.pipe(babel({
presets : ['#babel/preset-react']
}))
.pipe(concat('test.js'))
.pipe(gulp.dest('./dist/js'))
.pipe(terser())
.pipe(rename('test.min.js'))
.pipe(gulp.dest('./dist/js')) ;
});
How do I get babel to do its job?

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!