I am trying to run Karma-babel-preprocessor and a straight forward ES6 generator:
//require('babel/polyfill');
describe("how Generators work", function() {
it("will allow generator functions", function() {
/*function * numbers() {
yield 1;
yield 2;
yield 3;
};*/
let numbers = {
[Symbol.iterator]:function*(){
yield 1;
yield 2;
yield 3;
}
}
let sum = 0;
for(n of numbers){
sum += n;
}
expect(sum).toBe(6);
});
});
From this I generated my test files (ES6 => ES5) with babel:
babel src --watch --out-dir tests
Then I run karma start I get error:
ReferenceError: regeneratorRuntime is not defined".
Relevant bits in karma.conf.js:
// list of files / patterns to load in the browser
files: [
'test-main.js',
{pattern: 'tests/*.js', included: true}
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/*.js': ['babel']
},
'babelPreprocessor': {
options: {
sourceMap: 'inline'
},
filename: function(file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function(file) {
return file.originalPath;
}
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
Full project on github
I am able to use many ES6 features including arrows. Just no go on Generators.
Node js Env - updated December 2015
This question has already been answered, please see accepted answer UNLESS running within NodeJS environment.
If like myself, you had the same error message: 'ReferenceError: regeneratorRuntime is not defined' but were running Babel within a NodeJS environment, then simply doing the following will likely solve your problem:
npm install babel-polyfill --save
Then insert the following require statement towards the top of the affected module to obtain required (generator) behaviour:
require("babel-polyfill");
This should be all you need, just importing the module adds required polyfill behaviour at runtime.
Similar to the post by arcseldon, I was running Babel within a NodeJS environment and getting the same error message 'ReferenceError: regeneratorRuntime is not defined'. While installing babel-polyfill does work, I went with #babel/plugin-transform-runtime instead.
#babel/plugin-transform-runtime
It needs to be installed in two ways ... first as a dev dependency:
npm install --save-dev #babel/plugin-transform-runtime
and second as a production dependency:
npm install --save #babel/runtime
And then there needs to be one simple addition to your .babelrc file:
{
"plugins": ["#babel/plugin-transform-runtime"]
}
These additions give ES6 authoring functionality without the ReferenceError.
While I'm taking a different approach** to using Karma with Babel in my project, I suspect you're having the same problem I was: the Babel polyfill is not being loaded, and so you're not getting the functionality it supports (including the custom regenerator runtime that Babel uses to make generators work).
One approach would be to find a way to include the polyfill, perhaps by feeding it to Karma via the files array:
files: [
'path/to/browser-polyfill.js', // edited: polyfill => browser-polyfill per P.Brian.Mackey's answer
...
An alternate approach may be to use Babel's runtime transformer [edit: on rereading the docs, this will not work unless you then browserify/webpack/etc. to process the require() calls created by the transformer]; per its docs,
The runtime optional transformer does three things:
Automatically requires babel-runtime/regenerator when you use generators/async functions.
Automatically requires babel-runtime/core-js and maps ES6 static methods and built-ins.
Removes the inline babel helpers and uses the module babel-runtime/helpers instead.
I have no experience with this, but I suspect you would do so by including the optional: ['runtime'] option from the Babel docs in your babelPreprocessor config, viz.:
'babelPreprocessor': {
options: {
optional: ['runtime'], // per http://babeljs.io/docs/usage/options/
sourceMap: 'inline'
},
...
(** I'm currently using jspm + jspm-karma + some config to get the Babel polyfill to load in SystemJS; ask if relevant and I'll expound.)
I modified karma.conf.js to add browser-polyfill as mentioned in the Docs Link:
files: [
'node_modules/babel/browser-polyfill.js',
'test-main.js',
{pattern: 'tests/*.js', included: true}
],
After this modification, the following unit test works in Karma:
describe("how Generators work", function() {
it("will allow generator functions", function() {
/*function* numbers(){
yield 1;
yield 2;
yield 3;
};*///Simplified syntax does not work
let numbers = {
[Symbol.iterator]:function*(){
yield 1;
yield 2;
yield 3;
}
}
let sum = 0;
for(let num of numbers){
sum += num;
}
expect(sum).toBe(6);
});
});
If you use React, adding polyfills from create-react-app worked for me.
yarn add --dev react-app-polyfill
Then add the following lines to webpack.config.js
entry: {
app: [
'react-app-polyfill/ie9', // Only if you want to support IE 9
'react-app-polyfill/stable',
'./src/index.jsx',
],
},
See more examples on the react-app-polyfill GitHub page.
Related
I want to avoid this:
const SomeMethod = require('../shared/SomeMethod')
And instead use something more modern like this:
import { SomeMethod } from '/shared'
(under the hood): the /shared directory includes an index file of course, returning the object with the SomeMethod property which is also includes to a file.
As I am using JEST, I need two things to get around: 1 is that the node installed supports ES6 imports and 2 is that JEST will be familiar with relative path - notice that I have used the **/**shared so it means - go to the src directory and start from there.
But how to achieve this?
You can achieve this using babel. According to the documentation of jest, you need to do the following
yarn add --dev babel-jest #babel/core #babel/preset-env
and then create babel.config.js at the root of your project with the following content
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
You can look into the documentation for more
Here is a step by step process of the same which is addressing the same problem
In order to use absolute path for Jest add the following line in jest.config.js
module.exports = {
moduleDirectories: ['node_modules', 'src'],
...
};
here, src is considered as the root. You may need to change this one according to your folder name.
For more information you can follow this article
Nuxt 2.12.2 throw error on build when trying to use object?.key.
Module parse failed: Unexpected token (311:25) friendly-errors 10:36:40
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
So it because babel in Nuxt configured to support older browsers like IE9 that I did not need in my project.
In another project, I just put .bablelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 Chrome versions"]
}
}]
]
}
but in Nuxt .bablelrc are disabled. so how can I make optional chaining operator work ?
by telling Nuxt to support just modern browsers. or added the #babel/plugin-proposal-optional-chaining
As Nuxtjs Doc describe, .babelrc is ignored by default.
I solved this question by the below config.
// in nuxt.config.js
{
// ...
build: {
// ....
babel: {
plugins: [
'#babel/plugin-proposal-optional-chaining'
]
}
}
}
Of course, before that, you should install #babel/plugin-proposal-optional-chaining
npm i -D #babel/plugin-proposal-optional-chaining
I hope it helps you.
Try vue-template-babel-compiler
It uses Babel to enable Optional Chaining(?.), Nullish Coalescing(??) and many new ES syntax for Vue.js SFC.
Github Repo: vue-template-babel-compiler
DEMO
Usage
1. Install
npm install vue-template-babel-compiler --save-dev
2. Config
1. Vue-CLI
DEMO project for Vue-CLI
2. Nuxt.js
DEMO project for Nuxt.js
// nuxt.config.js
export default {
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
loaders: {
vue: {
compiler: require('vue-template-babel-compiler')
}
},
},
// ...
}
Please refer to REAMDE for detail usage
Support for Vue-CLI, Nuxt.js, Webpack , any environment use vue-loader v15+.
Following on from this question I have set up my Webpack 4 config to handle babel-loader like this
{
module : {
rules : [{
test : /\.js$/,
// Some module should not be transpiled by Babel
// See https://github.com/zloirock/core-js/issues/743#issuecomment-572074215
exclude: ['/node_modules/', /\bcore-js\b/, /\bwebpack\/buildin\b/, /#babel\/runtime-corejs3/],
loader : "babel-loader",
options : {
babelrc : false,
// Fixes "TypeError: __webpack_require__(...) is not a function"
// https://github.com/webpack/webpack/issues/9379#issuecomment-509628205
// https://babeljs.io/docs/en/options#sourcetype
sourceType : "unambiguous",
presets : [
["#babel/preset-env", {
// Webpack supports ES Modules out of the box and therefore doesn’t require
// import/export to be transpiled resulting in smaller builds, and better tree
// shaking. See https://webpack.js.org/guides/tree-shaking/#conclusion
modules : false,
// Adds specific imports for polyfills when they are used in each file.
// Take advantage of the fact that a bundler will load the polyfill only once.
useBuiltIns : "usage",
corejs : {
version : "3",
proposals : true
}
}]
]
}
}
}
}
When I run this in the browser I get this error which I do not understand:
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
TypeError: Cannot convert undefined or null to object
What is the fix for this? Following this question I have searched everywhere for code starting import 'core-js but cannot see it anywhere so have reached a dead end.
I had a similar problem and the reason was that Babel was transpiling my css-loader webpack plugin. Look here: MiniCssExtractPlugin error on entry point build
I have read of issues with transpiling node_modules with Nuxt, but the new Nuxt 2 is said to have solved this with a transpile option in the nuxt.config.js file.
https://nuxtjs.org/api/configuration-build/#transpile
Here is what I have:
export default {
router: {
base: '/',
},
build: {
transpile: [
'choices.js',
'lazysizes',
'swiper',
'vee-validate'
],
extractCSS: true
},
srcDir: 'src/',
performance: {
gzip: true
},
render: {
compressor: {
threshold: 100
}
},
dev: false
}
I removed a few things that are unrelated to make it easier to read.
When I run npm run build (nuxt build) the compiled JS files contain references to es6 and es7 code such as const and let etc when it should be var.
I have isolated this issue to be coming from Swiper. It appears to internally depend on something called Dom7 that seems to be causing the problem.
I am wanting to compile these node_modules dependencies to es5 if possible. I'm not sure my current setup is actually doing anything at all in that regard.
I believe Nuxt uses vue-app for Babel, but I even tried the following to no success:
babel: {
presets: [
'#babel/preset-env'
],
plugins: [
'#babel/plugin-syntax-dynamic-import'
]
}
Not much joy there either. Nothing appears differently in the final build.
I am using Nuxt 2.1.0
Any help appreciated. Thanks!
You also need to transpile Dom7, so the Nuxt config should have:
build: {
transpile: [
'swiper',
'dom7',
],
}
I have the exact same issue.
The vendor option under build is deprecated, so it's simply ignored I believe from what I read here https://medium.com/nuxt/nuxt-2-is-coming-oh-yeah-212c1a9e1a67#a688
I managed to isolate my case to the "swiper" library. If I remove that from my project, all references to let, const or class are gone. I've tried the transpile option too, but it does not seem to have any effect.
Will you try to exclude swiper from your project to see if we can isolate the issue?
I have a piece of code:
'use strict';
class ArticleModel {
constructor(options = {}) {
this.options = options
}
}
module.exports = ArticleModel
which results in the error Unexpected token = - I don't believe Babel is parsing this. Which babel 6 plugin is needed to parse default parameters in a function?
Edit 1 - this is my .babelrc file
{
"presets": [
"es2015",
"stage-0"
]
}
Edit 2 - I am not running babel from the same directory as .babelrc. I'm running babel from inside test/ where the structure looks like this:
/app
/test
/test/runner.js < -- this is what calls babel-core/register
.babelrc
Do I need to explicitly tell babel-core/register where .babelrc is? I assumed it rolled up a directory for it.
Edit 3 - changed babel/register to babel-core/register. Still get the same issue.
npm install babel-preset-es2015 --save-dev
Add the following line to your .babelrc file:
{
"presets": ["es2015"]
}
Did you try this?
How are you importing the module into the test? I had a similar problem when my tests started to break after upgrading from Babel 5 to 6. In my case it turned out that the problem was because the import has to referenced the default property in the imported lib.
The initiator of this Babel issue gives a good example: https://github.com/babel/babel/issues/2679