"Cant find variable Map", while I didn't use it [duplicate] - javascript

I'm using Angular 4, Webpack 2.4.1, Karma 1.6 and Jasmine 2.6.1 and am writing ES2015 not TypeScript
I've got a tiny angular demo app and I want to add unit tests. The demo app itself itself is working and Webpack is bundling everything correctly, but when I try to run the unit tests I see some errors in the console like this:
ReferenceError: Can't find variable: Map
at Static/js/app.welcome.js:2569
(app.welcome.js is the name of my component)
Webpack appears to be building my test bundle properly, Karma server is starting up correctly and PhantomJS is launching correctly, but then I see several of the Map errors.
I'm definitely not using the Map() constructor in my own code.
Here are my files -
app.welcome.js:
import {Component} from '#angular/core';
class WelcomeComponent {
constructor () {
this.welcomeMessage = 'Welcome to Angular 4';
}
}
WelcomeComponent.annotations = [
new Component({
selector: 'my-app',
template: '<h1>{{welcomeMessage}}</h1>'
})
];
export {WelcomeComponent};
app.welcome.spec.js:
import {TestBed} from '#angular/core/testing';
import {WelcomeComponent} from '../../js/app.welcome';
describe('The Welcome component', function () {
let component;
beforeEach(function() {
TestBed.configureTestingModule({
declarations: [WelcomeComponent]
});
const fixture = TestBed.createComponent(WelcomeComponent);
component = fixture.componentInstance;
});
it('should be a component', function() {
expect(component).toBeDefined();
});
it('should have a welcome message', function () {
expect(component.welcomeMessage).toEqual('Welcome to Angular 4');
});
});
karma.conf.js:
const webpack = require('webpack');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'./Static/js/**/*.js',
'./Static/test/**/*.spec.js'
],
exclude: [
'./Static/js/main.js'
],
preprocessors: {
'./Static/js/**/*.js': ['webpack'],
'./Static/test/**/*.spec.js': ['webpack']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity,
webpack: {
module: {
rules: [{
test: /\.js$/,
use: [{
loader: 'babel-loader',
options: { presets: ['es2015'] }
}]
}]
},
plugins: [
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, './src')
]
}
})
}
I've tried adding imports to my test file like import 'zone.js'; and import 'core-js/es6'; after reading other answers here, but this has not helped.
I've looked through Testing -ts - GUIDE and I don't appear to be missing anything huge from the earlier basic examples, but the problem is that all the official docs are geared towards TypeScript, while I want to use ES2015.
I understand that Map is an new type of object in ES2015 and not a variable as indicated by the error. Shouldn't Babel support this though?
Can anyone help?

This error is thrown because there's no Map in browsers. PhantomJS is used as Karma driver, and it doesn't support ES6 features.
If polyfills (e.g. core-js) aren't loaded in files that were included in tests, they should be loaded separately, for example via karma-es6-shim plugin:
...
frameworks: ['es6-shim', 'jasmine'],
...

This is what has worked for me:
I was using PhantonJs with karma and nightwatch for my testing . I was getting this error during JhantomJs initialization and as test were getting started because because there's no Map in browsers. PhantomJS is used as Karma driver, and it doesn't support ES6 features.
I tried to load polyfills but that did not help as well.
Then I saw that support for PhantonJs has long gone and felt it wont work. So I took an effort to replace PhantomJs with Chrome headless browser and surprisingly it was pretty easy to replace.
Here are the thing I did to make the change from PhantomJs to Chrome headless:
Package.json - puppeteer, chromedriver, karma-chrome-launcher as dependency
Add the following in karma.conf.js
const puppeteer = require('puppeteer');
process.env.CHROME_BIN = puppeteer.executablePath();
module.exports = function(config) {
config.set({
.
browsers: ['ChromeHeadless'],
.
});
Add/Edit the following in nightwatch.json
"chrome": {
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true,
"acceptSslCerts": true,
"chromeOptions": {
"args": ["--no-sandbox", "headless"]
}
}
This is something which has worked for me; may or may not work for you depending on the kind of side things you are using with JhantomJs for testing. Nevertheless should helpful for anyone who is trying to move away PhantomJs.

Related

Rollup UMD Module Reference to Named Imports is Undefined

I had a published component library (my-components) that had a specific component (Compare) in it, along w/ other components and utilities that were used in a main application. We use rollup and create several different output formats, one of which is UMD (required by one of the teams using my-components).
The component (Compare) was starting to become large, so it was moved out on its own. The rollup build was based off of what was used for my-components. After moving it out to its own repository to be built as its own component, it now had a dependency on my-components. When used in the main application (CRA app), everything works as expected. However, when the team who uses the UMD module tried to use the Compare app, they started to get errors:
Cannot read properties of undefined (reading someService)
The code in Compare is:
import {someService, somethingElse} from 'my-components';
. . .
someService.doSomething();
I saw the following warning during the build:
WARNING: { code: 'MISSING_GLOBAL_NAME', guess: 'myComponents', message: 'No name was provided for external module \'my-components\' in output.globals - guessing \'myComponents\'' }
So I explicitly added a global entry for it.
When I looked at the resulting code in the UMD module, the code looked like:
myComponents.someService.doSomething();
Why doesn't myComponents.someService resolve to the class that is exported from my-components?
My rollup.config.js looks like:
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.json'];
const umdGlobals = {
axios: 'axios',
lodash: '_',
react: 'React',
'react-dom': 'ReactDOM',
'my-components': 'myComponents'
};
export default [
{
input: 'src/components/index.js',
output: [
{ file: pkg.module, format: 'esm', sourcemap: true },
{ file: pkg.main, format: 'cjs', sourcemap: true },
{ file: pkg.umd, name: 'Compare', format: 'umd', sourcemap: true, globals: umdGlobals }
],
plugins: [
autoExternal(),
resolve({ extensions: EXTENSIONS, preferBuiltins: false, browser: true}),
commonjs({include: ['node_modules/**']),
babel({
babelHelpers: 'bundled',
babelrc: false,
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-typescript'],
plugins: ['#babel/plugin-transform-arrow-functions', '#babel/plugin-proposal-object-rest-spread', '#babel/plugin-proposal-class-properties],
extensions: EXTENSIONS,
exclude: 'node_modules/**'
}),
json(),
requireContext(),
internal(['classnames', 'pluralize'])
]
}
];
I tried to put my-components inside of internal(), and remove it from the global list, but that started to give other warnings that I think were the result of a dependency inside of it, and would throw errors when the bundle was used anyway.
Any advice on what I may be missing? Is there something wrong w/ the output from the my-components that I should be trying to fix in its rollup config, or is there something I can do in my rollup config for Compare?
Any help is greatly appreciated.

Can't import the named export 'Directive' from non EcmaScript module (only default export is available)

this is a ionic angular project that i'm working on, i'm using ng-lazyload-image plugin Link. when i start compiling it showing errors like this.
Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19
Can't import the named export 'Directive' from non EcmaScript module (only default export is available)
This means your bundler resolves .mjs files, however it doesn't know that they are ESM modules. On webpack, you can add the following to rules.
webpack.config.js (in project root)
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
}
]
}
}
}
https://webpack.js.org/configuration/
EDIT: Found a solution for craco.config.js
module.exports = {
webpack: {
configure: (webpackConfig) => {
webpackConfig.module.rules.push({
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
});
return webpackConfig;
},
plugins: [
// Inject the "__DEV__" global variable.
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== "production",
})
],
},
};
The answer of #Joosep.P works, but for someone with laravel and webpackmix the following is the way to go. In webpack.mix.js file add the following:
mix.webpackConfig({
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
}
]
}
});
Just posting it as another answer as it may help someone else or me to find the solution with laravel and webpackmix easily in the future. Thanks.
It probably has to do with different Angular versions.
If ng-lazyload-image is using Angular 13 and your own project is using a lower version this will happen. There are some breaking changes since Angular 13.
If ng-lazyload-image is using Angular 13 there are no es2015 files generated for it's npm package and your compiler is still looking for them.
An option to solve this would be to use a lower version of the ng-lazyload-image package or update your own Angular to Angular 13+

How to get Rollup to transform require() calls?

I'm trying to build my project using Rollup. I got most of it working (including Angular 2), but I'm unable to transform some of my polyfills, since they have calls to require() in them. Even with the rollup-plugin-node-resolve and rollup-plugin-commonjs it won't touch the requires at all.
So how can I transform them? A workaround I could use is to Browserify the polyfills and then include the browserified bundle in the rollup process, but that requires an awfully lot of extra plugins and isn't exactly a clean solution, especially since I thought that Rollup should be able to understand CommonJS.
Here is some test code for Node.js:
"use strict";
let rollup = require("rollup");
let fs = require("fs");
let resolve = require("rollup-plugin-node-resolve");
let commonjs = require("rollup-plugin-commonjs");
rollup.rollup({
entry: "src/main.js",
plugins: [
resolve({
jsnext: true,
main: true
}),
commonjs({
include: '**', // also tried src/** node_modules/** and a lot of other stuff.
// Leaving this undefined stops rollup from working
}),
]
}).then(function(bundle) {
bundle.write({
format: "iife",
dest: "www/bundle.js"
})
});
Then using a simple file as src/main.js that just contains the line require("./some-file.js"); and a src/some-file.js that contains anything demonstrates the problem.
I solved it with the help of the nice guys at rollup-gitter.
I needed to add a moduleName to the bundle.write options like so:
bundle.write({
format: "iife",
dest: "www/bundle.js"
moduleName: "someModule"
})

Karma/systemjs not looking in node_modules directory when trying to run tests

I'm trying to run tests using karma/jasmine/systemjs with Angular 2 and typescript. I previously had it working without systemjs/typescript using babel.
I also got it working transpiling typescript to es6 and using the same karma setup without using systemjs.
I want to use systemjs, and I don't want to have to do transpile twice, so now I'm trying to use systemjs with karma. (using karma-system.js).
The error I'm getting is:
Error: XHR error (404 Not Found) loading /path/to/project/angular2/core.js
For whatever reason, karma/systemjs is not looking in the node_modules directory for angular, and I don't want to hard code that into my project files.
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
plugins: ['karma-systemjs', 'karma-jasmine', 'karma-chrome-launcher'],
frameworks: ['systemjs', 'jasmine'],
files: [
'client/**/*.spec.js',
'client/**/**/*.spec.js',
'server/**/*.spec.js',
'server/**/**/*.spec.js'
],
exclude: [
'node_modules/',
'client/node_modules/*',
'client/node_modules/**/*.spec.js',
'server/node_modules/*'
],
preprocessors: {},
systemjs: {
configFile: 'system.conf.js',
serveFiles: [
'client/**/*.js',
'server/**/*.js',
],
config: {
defaultJSExtensions: true
}
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
system.conf.js
System.config({
paths: {
'systemjs': 'node_modules/systemjs/dist/system.js',
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js'
}
});
In my typescript file, I'm loading angular core like this.
import { Component, View } from 'angular2/core';
and it gets transpiled to:
System.register(['angular2/core'], function(exports_1) {
I have tried adding a baseUrl to my systemjs config, it does not seem to do anything.
I have been "googling" and searching stack for a few hours now. I've looked at How to configure karma and systemjs to run tests for angular ES6 transpiled by traceur into amd format ES5 modules and Angular and ES6: Karma Testing with SystemJS and still have not fixed the issue.
in your system.conf.js file you should define a path for all angular modules like this:
System.config({
paths: {
'angular2/*': 'node_modules/angular2/bundles/*.js',
}
});

Configure karma.js to work with react and ES6

Im try to develop a react module with ES6 and couldn't find any generator for that, so i had to make it from a basic one. I was able to config almost everything, but im have a lot of problems try to configure karma, to test my module.
This is my karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-03-17 using
// generator-karma 0.9.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['commonjs', 'mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'node_modules/react/react.js',
'lib/**/*.js',
'test/**/*.js'
],
preprocessors: {
'lib/**/*.cjsx': ['cjsx'],
'test/**/*.cjsx': ['cjsx'],
'lib/**/*.js': ['babel', 'commonjs'],
'test/**/*.js': ['babel', 'commonjs']
},
babelPreprocessor: {
options: {
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'Chrome', 'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-commonjs',
'karma-cjsx-preprocessor',
'karma-babel-preprocessor',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-mocha',
'karma-chai'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
At this point i have the following error
Chrome 42.0.2311 (Mac OS X 10.10.2) ERROR
Uncaught ReferenceError: module is not defined
at /Users/admin/workspace/open_source/react-component-inspector/node_modules/react/react.js:1
and if i remove the react ref from files section i get this other error
PhantomJS 1.9.8 (Mac OS X) ERROR
Uncaught Error: Could not find module 'react' from '/Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js'
at /Users/admin/workspace/open_source/react-component-inspector/node_modules/karma-commonjs/client/commonjs_bridge.js:85
And if i remove the commonJS i get
PhantomJS 1.9.8 (Mac OS X) ERROR
ReferenceError: Can't find variable: exports
at /Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js:5
Or al least can anyone recommend me a yo generator with karma, ES6, jsx, to build a module, not a web app?
Thanks for the help
I believe you just need to add the react file's path to the list of preprocessor files. This is because the react file is also using the commonjs format just like your app's files, and when that file gets loaded in chrome, unlike node, the browser has no notion of where the "module" object came from. Updated excerpt from your code below.
// list of files / patterns to load in the browser
files: [
'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'node_modules/react/react.js',
'lib/**/*.js',
'test/**/*.js'
],
preprocessors: {
// you can probably leave off babel here.
'node_modules/react/react.js': ['babel', 'commonjs'],
'lib/**/*.cjsx': ['cjsx'],
'test/**/*.cjsx': ['cjsx'],
'lib/**/*.js': ['babel', 'commonjs'],
'test/**/*.js': ['babel', 'commonjs']
},

Categories