Karma+Mocha+Browserify+ES6 testing stack setup problems - javascript

I am trying to create a testable front-end project along these guidelines:
React component architecture with __test__ folders in each component folder;
tests use ES6 modules;
browserify bundles everything into one file while babelify transpiles ES6;
karma uses the bundle for testing.
This is my karma.conf.js:
module.exports = function (karma) {
const testFiles = __dirname + '/proj/static/src/**/__tests__/*.js';
karma.set({
frameworks: ['browserify', 'mocha'],
browsers: ['Chrome'],
files: [
testFiles
],
logLevel: 'LOG_DEBUG',
preprocessors: {
testFiles: ['browserify'],
},
reporters: ['dots'],
singleRun: true,
browserify: {
debug: true,
transform: [ 'babelify' ]
},
});
};
This is my .babelrc
{
presets: ['es2015', 'react']
}
However, after launching karma, I get this error:
...
Uncaught SyntaxError: Unexpected token import
at proj/static/src/js/some-component/__tests__/some.test.js:1
Clearly the code doesn't get transpiled. I've read multiple tutorials, and all use different technologies. Any ideas how to fix the problem?
P.S. I am still very fresh with TDD in the front-end.
Edit
These are the installed npm dependencies:
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babelify": "^7.3.0",
"browserify": "^13.1.1",
"expect": "^1.20.2",
"karma": "^1.3.0",
"karma-browserify": "^5.1.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-mocha": "^1.3.0",
"mocha": "^3.1.2",
"reactify": "^1.1.1",
"watchify": "^3.7.0"

The problem is that testFiles is the value of the key in the preprocessors configuration. You need the value of the key to be a glob that matches the files that are to be preprocessed. No files are being matched, so no files are being preprocessed.
I would try this:
preprocessors: {
'**/*.js': ['browserify']
}
Your question doesn't go into detail about your project's directory structure, so I've suggested a glob that matches all .js files. You could refine it to match only your source files that need to be transpiled.
Be aware that the glob will need to match all of your source files - not just the tests.

Related

Cannot use import statement outside a module in /node_modules

I'm in the process of migrating some node packages which has become quite a headache.
Currently this is what my package.json looks like:
{
//These are the updated dependencies and Jest configurations
"dependencies": {
"#google-cloud/logging-winston": "^4.0.2",
"#google-cloud/secret-manager": "^3.2.3",
"#google-cloud/storage": "^5.7.0",
"#nestjs/common": "^8.2.3",
"#nestjs/config": "^1.1.5",
"#nestjs/core": "^8.2.3",
"#nestjs/jwt": "^8.0.0",
"#nestjs/mongoose": "^9.0.1",
"#nestjs/passport": "^8.0.1",
"#nestjs/platform-express": "^8.2.3",
"bcrypt": "^5.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"dayjs": "^1.9.7",
"helmet": "^4.2.0",
"mongoose": "^6.0.14",
"nanoid": "^3.1.20",
"nest-winston": "^1.4.0",
"p-all": "^3.0.0",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.4.0",
"winston": "^3.3.3"
},
"devDependencies": {
"#nestjs/cli": "^8.1.5",
"#nestjs/schematics": "^8.0.5",
"#nestjs/testing": "^8.2.3",
"#types/bcrypt": "^5.0.0",
"#types/express": "^4.17.13",
"#types/jest": "^27.0.3",
"#types/multer": "^1.4.7",
"#types/node": "^16.11.11",
"#types/passport-jwt": "^3.0.3",
"#types/passport-local": "^1.0.33",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.6.1",
"#typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^27.4.3",
"jest-mock": "^27.4.2",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^27.1.0",
"ts-loader": "^9.2.6",
"ts-node": "^10.4.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.5.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleDirectories": [
"node_modules",
"src"
],
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coveragePathIgnorePatterns": [
".module.ts",
"main.ts",
"env-var-names.ts",
".d.ts",
".types.ts",
".e2e-spec.ts"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node",
"resetMocks": true,
"resetModules": true
}
}
When I try to run Jest, I get the following error relating to /node_modules
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/{username}/{project_directory}/node_modules/mongodb/src/bson.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import type {
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (../node_modules/mongodb/src/bson.ts:8:12)
So within our team, we've been able to fix it by changing a part of the Jest configuration from:
"moduleDirectories": [
"node_modules",
"src"
],
To so:
"moduleDirectories": [
"node_modules",
],
We also had to change our import paths back to relative. This gets rid of the error and is working fine, however we are a bit stumped as to why this works? Does anyone have any insight they could share?
Thank you!
I faced the same issue today and was totally mad that mongoose v5 was running without any problems and v6 gave me this freaking error. Luckily after 2-3 hours of tilting at windmills I found a solution (works for me at least).
All I had to do was adding literally one word to jest.config.js.
// before
moduleDirectories: ['node_modules', 'src']
// after
moduleDirectories: ['node_modules', '<rootDir>/src']
I think that problem occurred because of the location of bson.ts file. It lays under /node_modules/mongodb/src/bson, the path has src in it so I suppose it caused conflicts with jest config where we match src. Usage of <rootDir> fixes out problem cuz it eliminates paths that don't start in root directory and testing works fine.
It seems that you didn't enable the es6 import/export. Add this to your package.json
"type": "module"

using gulp with webpack-stream and babel loader to convert jsx

I'm building a website in Wordpress and I am trying to use gulp, webpack-stream, and babel-loader to convert JSX to JS (I was successful at using gulp to sass my CSS, so I removed that code).
Whenever I run the gulp command in terminal to convert the JSX, I get this incorrect output in the generated Javascript file:
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";n.r(t);n(1);console.log("ugh")},function(e,t){console.log("test running")}]);
I can't figure out if I'm getting this error because I'm missing vital packages or if something else is wrong with my gulp commands.
Here is my package.json's dependencies
{
"devDependencies": {
"#babel/core": "^7.11.4",
"#babel/preset-env": "^7.11.0",
"#babel/register": "^7.10.5",
"#wordpress/browserslist-config": "^2.7.0",
"autoprefixer": "^9.8.6",
"babel-loader": "^8.1.0",
"babelify": "^10.0.0",
"browserify": "^17.0.0",
"browserslist": "^4.14.0",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-postcss": "^8.0.0",
"gulp-sass": "^4.1.0",
"gulp-sourcemaps": "^2.6.5",
"gulp-terser": "^1.4.0",
"webpack-stream": "^6.1.0"
},
"browserslist": [
"extends #wordpress/browserslist-config"
]
}
Here is my gulpfile.babel.js file:
// load gulp
import gulp from 'gulp';
// utility
import sourcemaps from 'gulp-sourcemaps';
// css-related
import sass from 'gulp-sass';
import postcss from 'gulp-postcss';
import autoprefixer from 'autoprefixer';
// js-related
import webpack from 'webpack-stream';
// project
const paths = {
scripts: {
src: 'src/scripts/bundle.js',
dest: './build/js/'
}
}
// enable javasript
export const scripts = (done) => {
return gulp.src( paths.scripts.src )
.pipe( webpack({
// module: {
// rules: [
// {
// test: /\.js$/,
// use: {
// loader: 'babel-loader',
// options: {
// presets: ['#babel/preset-env']
// }
// }
// }
// ]
// },
output: {
filename: 'bundle.js'
}
}) )
.pipe( gulp.dest( paths.scripts.dest ) );
done();
}
I commented out the webpack module items because I was eliminating the possible reasons for why it wasn't working. When I commented out webpack, the code "worked" in that it copied the file over to the build folder.
Here is the bundle.js file that contains JSX
console.log('ugh');
import './components/test';
let x = 0;
and here is what test.js contains
console.log("test running");
I also received the following message inside terminal:
(node:13196) [DEP0097] DeprecationWarning: Using a domain property in MakeCallback is deprecated. Use the async_context variant of MakeCallback or the AsyncResource class instead.
[22:53:54] Version: webpack 4.44.2
Built at: 10/20/2020 10:53:54 PM
Asset Size Chunks Chunk Names
bundle.js 1020 bytes 0 [emitted] main
Entrypoint main = bundle.js
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
[22:53:54] Finished 'scripts' after 1.69 s
I'm totally new to using node, npm, and gulp, and have been following tutorials as best I can to try to get this to work, but every tutorial is either old, or I end up with garbage code in the destination file. I'm also the lone developer and designer, and I desperately need some feedback/assistance. I would be forever grateful to whoever can help me get this to work properly, and am happy to provide any additional information in order to figure this out.

Jest encountered an unexpected token when testing a Vue single file component

I have a vue application with single file components and i want to add unit tests to test the components. I'm trying to use jest like described here but i keep getting the error "Jest encountered an unexpected token" with the following details:
/some_path/MyRecipe.vue:1
<template>
^
SyntaxError: Unexpected token <
1 | import { shallowMount } from "#vue/test-utils"
> 2 | import MyRecipe from "../src/components/MyRecipe.vue"
| ^
3 |
4 | describe('MyRecipe', () => {
5 | test('is a Vue instance', () => {
at Runtime._execModule (node_modules/jest-runtime/build/index.js:1166:56)
at Object.<anonymous> (__tests__/MyRecipe.test.js:2:1)
After some research (e.g. from here) I gather that this is probably due to jest expecting a .js file, but the .vue single file components have html, javascript and css in them, usually dealt with by webpack and vue-loader. I've tried to follow jest configurations from various tutorials to make jest use vue-jest to transform .vue files, but the error persists. This is my package.json file (unnecessary parts removed):
{
"name": "all-recipes ",
"version": "0.1.0",
"private": true,
"scripts": {
// ...
"test": "jest"
},
"dependencies": {
// ...
"core-js": "^3.4.3",
"vue": "^2.6.10"
// ...
},
"devDependencies": {
"#vue/cli-plugin-babel": "^4.1.0",
"#vue/cli-plugin-eslint": "^4.1.0",
"#vue/cli-service": "^4.1.0",
"#vue/test-utils": "^1.0.3",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^10.0.3",
"babel-jest": "^26.0.1",
// ...
"jest": "^26.0.1",
"jest-serializer-vue": "^2.0.2",
"vue-jest": "^3.0.5",
"vue-template-compiler": "^2.6.10",
"vue-test-utils": "^1.0.0-beta.11"
},
// ...
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.,(vue)$": "vue-jest",
"^.+\\.js$": "babel-jest"
},
"snapshotSerializers": [
"jest-serializer-vue"
]
}
}
Any idea what might be wrong, or some tips on how to debug this?
EDIT: I have looked into this question and I don't believe the answer there would solve my problem since what I am trying to import is a .vue file and not an .html file.
EDIT 2: I have a feeling that jest is somehow just not picking up the transforms, because removing them from package.json doesn't change anything.
EDIT 3: No, jest is correctly using vue-jest for transforming. If I uninstall vue-jest and try running the test again, jest complains that vue-jest is missing.
The solution to my problem turns out to be a bit anti-climatic.
The problem was that my regexp string to recognize .vue files was wrong and didn't pick up my MyRecipe.vue file. Therefore, vue-jest wasn't used to transform it for jest to interpret, hence the trouble understanding that the file in question started with a very non-js line; <template>. The regexp that works is ^[^.]+.vue$, so the transform section of my package.json file becomes
{
// ...
"jest": {
// ...
"transform": {
"^[^.]+.vue$": "vue-jest",
"^.+\\.js$": "babel-jest"
},
// ...
}
}
Met same issuesome time ago. What i found.
The problem was in the short note of template v-slot
template(v-slot:body)
It works to compile, but Jest throws an error
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
There was two ways i fount to solve this:
Edit my jest.config.js, like this
globals: {
'vue-jest': {
pug: {
doctype: 'html',
},
},
},
Write a full note like this
template(v-slot:body="")
What worked for me was changing the transform of the vue-jest to what is shown in the documentation.
https://github.com/vuejs/vue-jest
so try using "^.+\\.vue$": "vue-jest" instead of "^[^.]+.vue$": "vue-jest"
full config might look like this
{
"jest": {
"moduleFileExtensions": ["js", "json", "vue"],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest"
}
}
}
I faced same issues tried many solution but none of them work ..below is following workaround in my case
Check package json has following dev dependency entries and jest configurations
"devDependencies": {
"babel-jest": "^23.6.0",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-unit-jest": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/eslint-config-airbnb": "^5.0.2",
"#vue/test-utils": "^1.0.3",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-vue": "^6.2.2",
},
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue"
],
"transform": {
"^.+\\.vue$": "vue-jest"
},
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"snapshotSerializers": [
"jest-serializer-vue"
],
"testMatch": [
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.
(js|jsx|ts|tsx)"
],
"testURL": "http://localhost/"
}
Check babel.config.js
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
],
};
check jest.config.js
module.exports = {
preset: '#vue/cli-plugin-unit-jest',
};
You need to install vue-jest (https://github.com/vuejs/vue-jest) with
npm install -D #vue/vue3-jest
Here are the available versions and their corresponding vue and jest versions
Vue version
Jest Version
Package
Vue 2
Jest <= 26
vue-jest#4
Vue 3
Jest <= 26
vue-jest#5
Vue 2
Jest 27
#vue/vue2-jest
Vue 3
Jest 27
#vue/vue3-jest
Then, you'll just have to update your jest configuration (in jest.config.ts for example) and add a transform section
"transform": {
"^.+\\.vue$": "#vue/vue3-jest"
}
Warning: be sure to update the npm install and the jest.config.ts with the vue-jest package that match your need!

Babel 7 - ReferenceError: regeneratorRuntime is not defined

I have an application that is a node backend and a react frontend.
I get the following error when i try to build/run my node application.
Node: v10.13.0
Error:
dist/index.js:314
regeneratorRuntime.mark(function _callee(productId) {
^
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": [ [
"#babel/preset-env", {
"targets": {
"node": "current"
},
}
], "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
webpack.config.js
{
mode: "development",
entry: "./src/index.js",
target: "node",
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: {
colors: true
},
devtool: "source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
sourceMapFilename: "index.js.map"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
}
],
},
node: {
__dirname: false,
__filename: false,
},
"plugins": [
new CleanWebpackPlugin(),
new WebpackShellPlugin({
onBuildStart: [],
onBuildEnd: ["nodemon dist/index.js"]
}),
]
},
package.json
"dependencies": {
"connect": "^3.6.6",
"cors": "^2.8.5",
"dotenv": "^6.1.0",
"express": "^4.16.4",
"hellojs": "^1.17.1",
"i18n-iso-countries": "^3.7.8",
"morgan": "^1.9.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"request": "^2.88.0",
"request-promise-native": "^1.0.5",
"serve-static": "^1.13.2",
"vhost": "^3.0.2"
},
"devDependencies": {
"#babel/cli": "^7.1.5",
"#babel/core": "^7.1.6",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"clean-webpack-plugin": "^1.0.0",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^1.0.1",
"eslint": "^5.9.0",
"eslint-config-google": "^0.10.0",
"eslint-loader": "^2.1.1",
"eslint-plugin-react": "^7.11.1",
"extract-loader": "^3.0.0",
"file-loader": "^2.0.0",
"node-sass": "^4.10.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.26.0",
"webpack-cli": "^3.1.2",
"webpack-node-externals": "^1.7.2",
"webpack-shell-plugin": "^0.5.0"
}
Updated Answer:
If you are using Babel 7.4.0 or newer, then #babel/polyfill has been deprecated. Instead, you will want to use the following at the top of your main js file (likely index.js or similar):
import "core-js/stable";
import "regenerator-runtime/runtime";
Install these packages either with npm:
npm install --save core-js
npm install --save regenerator-runtime
or with yarn:
yarn add core-js
yarn add regenerator-runtime
Original Answer:
I just encountered this problem and came across the following solution:
In package.json I had #babel/polyfill as a dependency. However, in my index.js (My main js file) I had neglected to place the following line at the the top:
import '#babel/polyfill'
Once I imported it, everything worked fine.
I did not need to install babel-runtime as other answers are suggesting.
Babel 7.4.0 and later
There are two main configurations - one for apps and one for libraries.
Option 1: App
When to use: ✔ for applications ✔ global scope polyfills ✔ smallest bundle size ✔ selective inclusion via targets ✔ No need to process node_modules for polyfills
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage", // alternative mode: "entry"
"corejs": 3, // default would be 2
"targets": "> 0.25%, not dead"
// set your own target environment here (see Browserslist)
}
]
]
Install dependencies:
npm i --save-dev #babel/preset-env
npm i regenerator-runtime core-js // run-time dependencies
// regenerator-runtime: transform (async) generators and `async`/`await`
// core-js: other ECMAScript features like Promise, Set, etc.
#babel/preset-env selectively includes polyfills for targets, specified by a Browserslist query. There are two modes - try usage first (more convenient), else entry (more flexible and robust):
useBuiltIns 'usage': no need to import anything manually. All polyfills are added automatically based on their code usage in a file.
useBuiltIns 'entry': Add these import entries once (!) in your app - akin to #babel/polyfill:
import "regenerator-runtime/runtime";
import "core-js/stable"; // or more selective import, like "core-js/es/array"
Extension
For advanced cases, you might use #babel/transform-runtime (dev) and #babel/runtime (run-time) only for Babel helpers to reduce bundle size a bit more - called helper aliasing.
Option 2: Library
When to use: ✔ for libraries ✔ no global scope pollution ✔ includes all polyfills, not selective ✔ bigger bundle size neglectable
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true,
"corejs": 3
}
]
]
Install compile-time and run-time dependencies:
npm i --save-dev #babel/plugin-transform-runtime // only for build phase
npm i #babel/runtime // runtime babel helpers + just regenerator runtime
// OR (choose one!)
npm i #babel/runtime-corejs3
// also contains other JS polyfills (not only regenerator runtime)
// depends on core-js-pure ("ponyfills"/polyfills that don't pollute global scope)
See #babel/plugin-transform-runtime, #babel/runtime, #babel/runtime-corejs.
Extension
You can additionally use #babel/preset-env for syntax transpilation only, with useBuiltIns: false. As the library option does not use global polyfills, you might want to transpile node_modules as well - see the absoluteRuntime option.
Closing notes
Breaking Change: #babel/polyfill is deprecated starting with Babel 7.4.0.
Legacy: If you can't switch to core-js#3, set corejs option to 2 (see migrations). Install #babel/runtime-corejs2 in case of option 2 (#babel/plugin-transform-runtime).
Excellent summary in #9853 by Jovica Markoski
Currently, the library approach doesn't take selective targets into account - meaning you take locally scoped polyfills at the price of bigger bundle size (including all polyfills).
babel-polyfills is a new, experimental approach to inject different polyfills (not just core-js) with different strategies.
This also allows to selectively include locally scoped polyfills.
There is already a very good answer here (originally posted on the Babel6 question) which I will just translate to Yarn. Basically, you need babel runtime (NOT as a dev dependency) and the plugin transform-runtime
yarn add #babel/runtime
yarn add -D #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/transform-runtime"]
}
I had this error in my react project with webpack 4 and this was preventing the whole project to get rendered.
This is how I solved it:
Install plugin-transform-runtime:
npm install #babel/plugin-transform-runtime -D
Add plugin-transform-runtime to the plugin's list in the .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
["#babel/transform-runtime"] // <= Add it here
]
}
For me worked:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
}
I just solved this error when I imported babel-polyfill directly into the file that shows the error, for example, the error says "ReferenceError: regeneratorRuntime is not defined at /dist/models/usersSchema.js", so I use this in my usersSchema.js file:
require("babel-polyfill");
(you can use import "babel-polyfill";as well)
You will need to have the regeneratorRuntime.
Install this two packages - babel-plugin-transform-regenerator and babel-polyfill
Add the following Babel configuration via .babelrc
{
"plugins": ["transform-regenerator"]
}
React.js Users
If this issue faced you while using react (specifically while trying to use Async/Wait), then Valentino Gagliardi provided a detailed approach on his blog regarding how to address this issue

nomod errors when installing new angular modules

When I try to include braintree-angular into my gulp-angular project, I get the following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module notecards due to:
Error: [$injector:modulerr] Failed to instantiate module braintree-angular due to:
Error: [$injector:nomod] Module 'braintree-angular' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I routinely run into issues loading newly install modules in gulp-angular projects, and I believe it comes from a general lack of understanding in how gulp works. The gulp portion of this project was setup by a coworker. If someone could explain why I continue to see issues like this, it would be much appreciated!
I have checked the following:
The module is correctly installed in my /node_modules folder.
The module appears correctly in my package.json.
The entire folder is readable (I've previously had issues with file permissions causing this. This is not the case here.)
The braintree-angular files are not being loaded by gulp.
gulp/server.js
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
//var babel = require('gulp-babel');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if (baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
routes : routes
};
/*
* You can add a proxy to your backend by uncommenting the line below.
* You just have to configure a context which will we redirected and the target url.
* Example: $http.get('/users') requests will be automatically proxified.
*
* For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
*/
// server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', changeOrigin: true});
browserSync.instance = browserSync.init({
startPath: '/',
server : server,
browser: browser,
host: '192.168.0.20',
https: false,
port : parseInt(process.env.GULP_PORT) || 8684
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
var gulp = require('gulp');
var webserver = require('gulp-webserver');
gulp.task('webserver', function() {
gulp.src('src')
.pipe(webserver({
host: '0.0.0.0',
livereload: true,
directoryListing: true,
open: true
}));
});
gulpfile.js
/**
* Welcome to your gulpfile!
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function (file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function (file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
package.json
{
"name": "healthbydna",
"version": "0.0.0",
"dependencies": {
"angular-chart.js": "^1.0.3",
"babel": "^6.5.2",
"braintree-angular": "^1.5.0",
"gulp-babel": "^6.1.2",
"gulp-extend": "^0.2.0",
"gulp-if": "^2.0.0",
"gulp-ng-constant": "^1.1.0",
"jotted": "^1.5.1",
"lazypipe": "^1.0.1"
},
"scripts": {
"test": "gulp test"
},
"devDependencies": {
"babel-core": "^6.21.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-es2016": "^6.16.0",
"browser-sync": "~2.9.11",
"browser-sync-spa": "~1.0.3",
"chalk": "~1.1.1",
"del": "~2.0.2",
"eslint-plugin-angular": "~0.12.0",
"estraverse": "~4.1.0",
"gulp": "^3.9.1",
"gulp-angular-filesort": "~1.1.1",
"gulp-angular-templatecache": "~1.8.0",
"gulp-autoprefixer": "~3.0.2",
"gulp-eslint": "~1.0.0",
"gulp-filter": "~3.0.1",
"gulp-flatten": "~0.2.0",
"gulp-inject": "~3.0.0",
"gulp-load-plugins": "~0.10.0",
"gulp-minify-css": "~1.2.1",
"gulp-minify-html": "~1.0.4",
"gulp-ng-annotate": "~1.1.0",
"gulp-protractor": "~1.0.0",
"gulp-rename": "~1.2.2",
"gulp-replace": "~0.5.4",
"gulp-rev": "~6.0.1",
"gulp-rev-replace": "~0.4.2",
"gulp-sass": "~2.0.4",
"gulp-size": "~2.0.0",
"gulp-sourcemaps": "~1.6.0",
"gulp-uglify": "~1.4.1",
"gulp-useref": "~1.3.0",
"gulp-util": "~3.0.6",
"gulp-webserver": "^0.9.1",
"http-proxy-middleware": "~0.9.0",
"karma": "~0.13.10",
"karma-angular-filesort": "~1.0.0",
"karma-coverage": "~0.5.2",
"karma-jasmine": "~0.3.6",
"karma-ng-html2js-preprocessor": "~0.2.0",
"karma-phantomjs-launcher": "~0.2.1",
"lodash": "~3.10.1",
"main-bower-files": "~2.9.0",
"phantomjs": "~1.9.18",
"uglify-save-license": "~0.4.1",
"wiredep": "~2.2.2",
"wrench": "~1.5.8"
},
"engines": {
"node": ">=0.10.0"
}
}
Gulp is just a (very powerful) task runner, plain and simple. It does things you could do yourself, but you don't have the time for ;)
Node modules are not the same thing as Angular modules. Node modules have a broad scope and are for running general purpose code in the Node.js platform. That is, Javascript that runs outside of the typical web-browser setting. For example a desktop application, a loan calculator, a web server, a chat program, etc.
However, many Node modules are specifically for use with Angular and have a Bower counter-part. Bower packages are, indeed, for including directly in your webpage:
<script src="./bower_components/path/to/script.js" type="text/javascript"></script>
Why is there both a Node module AND a Bower package for a web module, you might ask? That's because of bundlers like Browserify and Webpack that let you actually use Node modules in your webpage. It does not appear that your project is setup for a bundler.
You want to either get the compiled js for your module (ideally by modifying your gulpfile to compile and/or concatenate the correct JS file from the node module's folder) or use Bower to download the already compiled JS, and modify the gulp file to include it into the concatenation process.
There are multiple files that make up the Gulp process for your project. Look for the 'build' task in one of those files. It should include the details about how vendor JS files are built. You want to modify it so that it is including the path to braintree-angular's JS file (if it exists)
Okay, the fix to this very specific issue was to remove braintree-angular from node_modules and install it via bower. I also need to lock the version to v1.3.0. I am unsure why this fixed it, so an explanation would be great :)
Gulp has nothing to do with Angular modules. From tasks you have published it is only used for localhost development and build not for any dependency injection.
Your problem is probably coming from not requiring dependency for module. You app.module should look something like this.
angular.module('app', [
'angular-svg-round-progress'
]);
And also make sure module is loaded before your app else instantiation will fail.

Categories

Resources