Here's what my .babelrc looks like. Obviously it doesn't work because of the regex in a JSON file:
{
"presets": ["es2015", "react"],
"plugins": ["transform-object-rest-spread"],
"only": [
'/client/**/*',
'/server/**/*',
/diy-fe-shared/ // <--- regex here breaks
]
}
Is there a way to use a regex here?
Maybe you can use regex in .babelrc like this: https://github.com/probablyup/markdown-to-jsx
Create .babelrc.js:
const plugins = [
'emotion',
];
if (process.env.NODE_ENV === 'production') {
plugins.push('transform-react-remove-prop-types');
}
module.exports = {
plugins,
presets: [
['es2015', {
loose: true,
modules: process.env.BABEL_ENV === 'esm' ? false : 'commonjs',
}],
'react',
'stage-2',
],
};
Then require .babelrc.js in .babelrc
{
"presets": ["./.babelrc.js"]
}
No, you cannot use regular expressions in .babelrc files. But you can in .babelrc.js files:
Rename your .babelrc to .babelrc.js and export your configuration object:
module.exports = {
"env": {
"production": {
"plugins": [/* Only run if webpack configures babel-loader's options.envName="production" */]
}
},
"presets": ["es2015", "react"],
"plugins": ["transform-object-rest-spread"],
"only": [
'/client/**/*',
'/server/**/*',
/diy-fe-shared/ // <--- regex here works
]
};
https://babeljs.io/docs/en/configuration#babelrcjs
Related
I use rollup to create multiple libs, rollup config file as below:
import terser from '#rollup/plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import { babel } from '#rollup/plugin-babel';
import eslint from '#rollup/plugin-eslint';
const distDir = "dist/libs"
const api = {
input: "src/libs/api/index.js",
external: ["axios"],
output: [
{
file: `${distDir}/api.umd.js`,
format: "umd",
name: 'Api',
globals: {axios: 'axios'}
},
{
file: `${distDir}/api.es.js`,
format: "es"
}
],
plugins: [
terser(),
babel({babelHelpers: 'runtime', exclude: 'node_modules/**'}),
nodeResolve({
browser:true,
}),
commonjs(),
eslint({
throwOnError: true,
throwOnWarning: true,
include: ['src/**'],
exclude: ['node_modules/**']
})
]
}
const test = {
...
}
export default ()=>{
return [
api, // it contains some polyfill
test // it also contains some polyfill
]
};
My .babelrc is:
{
"presets": [
["#babel/preset-env", {
"corejs": {"version": "3", "proposals": false},
"useBuiltIns": "usage"
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime"
]
]
}
Now, api and test contain some polyfill. Is there a way to extract the used polyfills of all modules to form a single umd file but not Full Function polyfill.Thank you.
I use Material UI and want to make the bundle size smaller by loading the components on demand.
I've got a Babel config in a .babelrc file.
At the moment the .babelrc looks like this:
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Now I need to add the following:
const plugins = [
[
'babel-plugin-import',
{
'libraryName': '#material-ui/core',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'core'
],
[
'babel-plugin-import',
{
'libraryName': '#material-ui/icons',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'icons'
]
];
module.exports = {plugins};
How can I do that ? It seems that .babelrc works differently to the .babelrc.js
As indicate in https://babeljs.io/docs/en/config-files:
For compatibility reasons, .babelrc is an alias for .babelrc.json.
So your first script is JSON format and the second one is CommonJS.
Mi suggestion is just copy the contents of plugins from your second script inside the "plugins" section of your first one, and use any JSON validation tool to make sure that the result is correct, see [1]
That being said I suggest that you use .babelrc.cjs (CommonJS) format as it is just javascript code can be formated easily using tools like prettier and support some features that JSON does not like comments, see [2]
[1] .babelrc or .babelrc.json
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
[
"babel-plugin-import",
{
"libraryName": "#material-ui/core",
"libraryDirectory": "esm",
"camel2DashComponentName": false
},
"core"
],
[
"babel-plugin-import",
{
"libraryName": "#material-ui/icons",
"libraryDirectory": "esm",
"camel2DashComponentName": false
},
"icons"
]
]
}
[2] .babelrc.js or .baberc.cjs
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [
["#babel/plugin-syntax-dynamic-import"],
["react-hot-loader/babel"],
["import", {
"libraryName": "antd",
"style": true
}],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
const presets
const plugins = [
[
'babel-plugin-import',
{
'libraryName': '#material-ui/core',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'core'
],
[
'babel-plugin-import',
{
'libraryName': '#material-ui/icons',
// Use "'libraryDirectory': ''," if your bundler does not support ES modules
'libraryDirectory': 'esm',
'camel2DashComponentName': false
},
'icons'
]
];
module.exports = {plugins};
I am trying to optimize my webpack bundle size by splitting it into two bundles: webpack-bundle.js, which contains my code, and vendor-bundle.js, which contains node modules and third party libraries. But after I successfully created two bundles, I am getting two errors in the browser regarding both bundles:
Uncaught ReferenceError: exports is not defined at vendor-bundle.self-879f615019647c756dc959f99d735b3a2534b00805364ae6fca0091d1190d62d.js?body=1:1
Uncaught TypeError: Cannot read property 'call' of undefined at I (webpack-bundle.self-78221fc03008c178fe970b69731594f14d651dab84e5cf928beacc805ebde79c.js?body=1:1)
This is my webpack.config.js.
const config = {
"entry": {
"webpack-bundle": "./app/registration",
},
"output": {
filename: "[name].js",
path: pathLib.resolve(__dirname, "../app/assets/webpack"),
},
"module": {
"rules": [
{
"exclude": /node_modules/,
"test": /\.jsx?$/,
"use": {
"loader": "babel-loader",
"options": {
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
}
}
],
},
"plugins": [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
}),
new UglifyJsPlugin(),
],
"optimization": {
"splitChunks": {
"cacheGroups": {
"vendor": {
"test": /node_modules/,
"chunks": "all",
"name": "vendor-bundle"
}
}
}
},
"resolve": {
"alias": {
"Lib": pathLib.resolve(__dirname, "app/lib/"),
"Shared": pathLib.resolve(__dirname, "app/shared/")
},
"extensions": [".js", ".jsx"]
},
"target": "node"
};
module.exports = config;
This is my .babelrc:
{
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
We use React, Rails, React on Rails, and Slim. To load webpack, I'd add this to my application.slim:
= javascript_include_tag 'vendor-bundle'
= javascript_include_tag 'webpack-bundle'
I want to be able to serve the two bundles I created. Is there anything wrong in the way I configured my webpack and split the bundle? Or should I install something else?
At the bottom of your webpack config, you have your target mode set to node
In node, module and module.exports both exist, but these don’t exist in the browser - this is what’s causing the error
If you remove this line, webpack will assume you’re targeting browsers instead, and will also transform this line for you - your bundles should then run in the browser as expected.
In their website, webpack shows plugin usage like this
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
I want to use babel plugin transform-async-to-generator, so I added it in babelrc file but I dont know this is enough, should I add it also webpack file ? If so how
I can not be sure if writing plugin in webpack config file required because right now I am getting runtime error and not sure if it works writing only in babelrc file.
my current webpack config file
var path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'partner/index.js'),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'partner_bundle.js'
},
target: 'web',
module: {
rules: [
{
test: /\.js$/, // Check for all js files
loader: 'babel-loader',
query: {
presets: [
'babel-preset-env',
'babel-preset-stage-0'
].map(require.resolve)
},
exclude: /node_modules\/(?!other-module)/
}
]
},
stats: {
colors: true
},
devtool: 'source-map',
resolve: { symlinks: false }
}
babelrc file
{
"presets": [
"env",
"stage-2"
],
"plugins": [
"transform-async-to-generator",
"transform-async-generator-functions",
[
"transform-runtime",
{
"helpers": false,
"polyfill": false,
"regenerator": true
}
]
]
}
Here you can see in my webpack config how I include the babel plugins:
test: /(\.jsx|\.js)$/, // JSX and JS files should be present.
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'babel-loader',
options: {
// Babel must be required like this to be able to use npm-link to link to shared code, see:
// https://stackoverflow.com/questions/34574403/how-to-set-resolve-for-babel-loader-presets/
presets: [
[node_modules + '/#babel/preset-env', {
// Ref: 1) http://2ality.com/2017/02/babel-preset-env.html
// 2) http://caniuse.com/usage-table
// In case it supports the browserlist in package.json, remove this here, see:
// https://github.com/babel/babel-preset-env/issues/149
"targets": {"browsers": ["> 4%", "safari 10", "ie 11", "iOS 9"]},
"modules": false,
"useBuiltIns": 'entry',
// "debug": true
}],
[node_modules + '/#babel/preset-react'],
],
plugins: [
node_modules + '/#babel/plugin-proposal-class-properties',
node_modules + '/#babel/plugin-proposal-object-rest-spread'].map(require.resolve)
}
}]
I use webpack to bundle modules react written in ES6. All have been worked until I added json-immutable plugin. There required is json-stream-stringify and there is a class:
class JSONStreamify extends CoStream {...}
module.exports = function(obj, replacer) {
return new JSONStreamify(obj, replacer);
};
webpack works good but not monify files because Uglify throw error
Unexpected token: name (JSONStreamify)
I found here information about module https://github.com/webpack-contrib/uglifyjs-webpack-plugin . I installed and added ecma support but still I have the same errors. I've trie remove I've tried add exclude node_modules but without results.
My webpack.config.js is
const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: {
backend: './src/backend.js',
frontend: './src/frontend.js',
},
output: {
path: path.resolve(__dirname,'./dist'),
filename: '[name].sakui.min.js'
},
externals: {
'jQuery':'jQuery',
'Foundation':'Foundation',
'react': 'React',
'react-dom': 'ReactDOM',
'redux': 'Redux',
'react-redux': 'ReactRedux',
'immutable': 'Immutable',
'lodash': '_',
'_': '_'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
"only": "src/**",
"presets": [
"env",
"react",
"es2017",
"stage-3"
],
"plugins": [["transform-class-properties", { "spec": true }],"transform-decorators-legacy","minify-simplify"],
"babelrc": false
}
}
}
]
},
plugins: [
new UglifyJSPlugin({
ecma: 6
})
]
}
Any hints how I can solve this problem? Maybe any external tool to minify files after webpack?
Solution:
one way what I found is transpile all with node_modules by babel to ES5 and it works.
my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: {
backend: './src/backend.js',
frontend: './src/frontend.js',
},
output: {
path: path.resolve(__dirname,'./dist'),
filename: '[name].sakui.min.js'
},
externals: {
'jQuery':'jQuery',
'Foundation':'Foundation',
'react': 'React',
'react-dom': 'ReactDOM',
'redux': 'Redux',
'react-redux': 'ReactRedux',
'immutable': 'Immutable',
'lodash': '_',
'_': '_'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
"presets": [
"env",
"react",
"es2017",
"stage-3"
],
"plugins": [["transform-class-properties", { "spec": true }],"transform-decorators-legacy"],
"babelrc": false
}
}
}
]
},
plugins: [
new UglifyJSPlugin()
]
}
Maybe will useful for someone.