Polymer 3 build yields 0-byte my-app.js - polymer

I seem to have encountered a problem similar to this.
file my-app.js:
import {PolymerElement, html} from "../node_modules/#polymer/polymer/polymer-element.js";
import "../node_modules/#polymer/polymer/lib/elements/dom-if.js";
import "../node_modules/#polymer/app-route/app-location.js";
import "../node_modules/#polymer/app-route/app-route.js";
class MyApp extends PolymerElement {
...
}
customElements.define('my-app',MyApp);
file polymer.json:
{
"entrypoint":"index.html"
,"shell":"src/my-app.js"
,"builds":[
{
"preset":"es5-bundled"
,"addServiceWorker": false
}
]
}
command polymer build produces file my-app.js with 0 byte. All other built files look correct according to my naked eyes (at least they are not truncated to 0 byte).
I then re-built the application with the following "dev" polymer.json:
"builds":[
{
"name": "dev",
"addServiceWorker": false,
"js": {"minify": false, "compile": false},
"css": {"minify": false},
"html": {"minify": false},
"bundle": false,
"addPushManifest": false
}
]
The built my-app.js looks correct with this "dev" configuration. However, browser's sources window highlights with red under score the first of the followings lines:
import {PolymerElement, html} from "../node_modules/#polymer/polymer/polymer-element.js";
import "../node_modules/#polymer/polymer/lib/elements/dom-if.js";
import "../node_modules/#polymer/app-route/app-location.js";
import "../node_modules/#polymer/app-route/app-route.js";
and console window prints this strange message:
Uncaught TypeError: Failed to resolve module specifier "#polymer/polymer/polymer-legacy.js". Relative references must start with either "/", "./", or "../". (index):1
I have searched all my .js files and directory ../node_modules/ and have not found any file containing polymer-legacy.js.
Helps will be much appreciated.
EDIT
Thank you for the attention!
These weird symptoms are caused by the stale polymer 1.6.0 which was installed in /usr/local/bin/polymer using yarn .
These issues are gone with polymer 1.7.2.

Related

JetBrains WebStorm Jest encountered an unexpected token

I have a problem with running a simple project in WebStorm IDE. This is what I get when I hit run:
Test suite failed to run
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.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/patryk/WebstormProjects/Case Converter/node_modules/hs-test-web/hstest/stage/stageTest.js:12
runner = new PureJsApplicationRunner();
^
SyntaxError: Unexpected token =
at ScriptTransformer._transformAndBuildScript (node_modules/jest/node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (node_modules/hs-test-web/hstest/index.js:1:110)
At this moment, my project contains just 1 html file. I tried reinstalling nodejs and npm, but that didn't work
Good time of day,
I've encoutered the same problem with one Edu project in WebStorm IDE - when i pressed the "check" button for task - i've got issue:
"test suite failed to run
Jest encountered an unexpected token ..."
How it was solved:
Please check if nodejs and npm installed - At IDE: File\Settings, section: Languages & frameworks > nodejs and npm section > at field: "Node interpreter" you'll find something like : "node /usr/bin/node" and at field: "Package manager" the value "npm /usr/share/npm"
In IDE - you need to expand "Project pane" and to choose view mode "Project Files" - then you need open the file "package.json",
initially this file contains the code:
{
"devDependencies": {
"#types/jest": "^23.3.12",
"hs-test-web": "https://github.com/hyperskill/hs-test-web/archive/release.tar.gz",
"jest": "^27.3.1",
"puppeteer": ">=8.0.0"
},
"scripts": {
"test": "jest"
}
}
You need to add the section for "jest" - please found the complete package.json below
{
"devDependencies": {
"#types/jest": "^23.3.12",
"hs-test-web": "https://github.com/hyperskill/hs-test-web/archive/release.tar.gz",
"jest": "^27.3.1",
"puppeteer": ">=8.0.0"
},
"scripts": {
"test": "jest"
},
"jest": {
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json"
],
"transform": {
"^.+\\.jsx?$": "babel-jest",
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"transformIgnorePatterns": ["/node_modules/(?!lodash-es)"],
"testRegex": "test/.*\\.spec\\.ts$"
}
}
So,i hope it help you.

#rollup/plugin-json with typescript not working

I have a valid appsettings.json file (according to jsonlint.com), I've set the tsconfig resolveJsonModule option to true. I'm importing #rollup/plugin-json and I've tried calling it at every position in the plugins chain. But I always get:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
So the plugin is firing (I think), but it can't parse the file, which seems to be valid. Rollup config looks like this:
import typescript from '#rollup/plugin-typescript';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from "#rollup/plugin-commonjs";
import dev from 'rollup-plugin-dev';
import copy from 'rollup-plugin-copy';
import replace from '#rollup/plugin-replace';
// Loaders for non-ts/js file types
import postcss from 'rollup-plugin-postcss';
import image from '#rollup/plugin-image';
import json from '#rollup/plugin-json';
console.log(`Node env is ${process.env.NODE_ENV}`);
// console.debug(process);
let isDevEnv = process.env.NODE_ENV === 'development';
let useMsw = process.env.USE_MSW;
const extensions = ['.cjs', '.js', '.jsx', '.json', '.ts', '.tsx', '.css', '.png'];
// const intro = useMsw
// ? 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = true'
// : 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = false';
const intro = `global = window; window.NODE_ENV = process.env.NODE_ENV; ${useMsw ? 'window.USE_MSW = true;' : ''}`;
export default {
input: [
'src/index.tsx'
],
output: {
intro: intro,
file: './dist/bundle.js',
format: 'es',
sourcemap: isDevEnv,
inlineDynamicImports: true,
},
plugins: [
postcss({}),
resolve({
extensions: extensions,
browser: true
}),
commonjs(),
typescript(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
image(),
copy({
targets: [
{src: './src/index.html', dest: './dist/'},
{src: './src/mockServiceWorker.js', dest: './dist/'}
],
verbose: true
}),
isDevEnv && dev('dist', {
host: 'localhost'
}),
json(),
]
};
tsconfig looks like this:
{
"compilerOptions": {
"declaration": false,
"module": "ESNext",
"noImplicitAny": true,
"target": "ES2015",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.tsx",
"src/**/*.ts",
"declaration.d.ts",
"src/components/TabularVIew/GridContainer/hooks"
],
"exclude": ["node_modules"]
}
and the actual json file looks like this:
{
"HUB_URL": "theHubUrl",
"AUTH_ENDPOINT": "https://localhost:44330/API/Dispatch/Authentication/v1.0/authenticate",
"POSITION_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/position",
"SUMMARY_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/summaries",
"GLOBAL_TLM": 1,
"PERIOD_LENGTH_MINUTES": 30,
"EFA_BLOCKS": [
[23,0,1,2],
[3,4,5,6],
[7,8,9,10],
[11,12,13,14],
[15,16,17,18],
[19,20,21,22]
]
}
and the rollup output is this:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
Pretty frustrating because on one line it says 'plugin json can't parse', then the next log line tells me I need plugin json???. Invalid file, file not found, plugin not installed, these I could understand. Possibly a clash between tsc and the plugin. Out of ideas..
Suggestions welcome.
Thanks.
The reason for that can be the json file encoding is utf8withbom. Try to encode the file as utf8.
Not really an answer, but the behaviour appears to be linked to some aggressive caching. Either by npm or typescript. I opened up the project in vscode, hosed node_modules, ran npm install, usual drill.. created a new JSON file, installed the rollup json plugin, and it built. Sum total of learning: 0;

"SyntaxError: Unexpected token export" using Jest with babel 7+

I'm trying to cover basic reducer with a test but it throws the error for export in my constants file:
FAIL jest/spec/reducers/RootReducer.spec.js
● Test suite failed to run
Jest encountered an unexpected token
Details:
project-root\js\src\constants\ActionTypes.js:2
export const LOCALE_REQUEST = 'ROOT/LOCALE_REQUEST';
^^^^^^
SyntaxError: Unexpected token export
1 | 'use strict';
2 |
> 3 | import { LOCALE_REQUEST_SUCCESS, ROUTING_REQUEST_SUCCESS } from '/js/src/constants/ActionTypes';
| ^
4 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (jest/spec/reducers/RootReducer.spec.js:3:1)
I'm running the tests from 'project-root\tests' folder
The js files that I want to test are located in 'project-root\js' folder
I believe this is the reason for the bug. Because the file I'm trying to import is outside of the tests folder it looks like it's not being transpiled
this is my package.json:
{
"name": "jest",
"version": "0.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-transform-modules-commonjs": "^7.2.0",
"#babel/preset-env": "^7.2.3",
"babel-core": "7.0.0-bridge.0",
"jest": "^23.6.0"
}
}
this is .babelrc:
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
this is jest.config.js:
module.exports = {
verbose: true,
transform: {
"^.+\\.jsx?$": "babel-jest"
},
bail: true,
browser: true,
cacheDirectory: '/tmp/jest',
collectCoverage: false,
roots: [
'<rootDir>/../js',
'<rootDir>/jest'
],
moduleNameMapper: {
'^(.*)/js/(.*)$': '<rootDir>/../js/$2'
},
testRegex: '(jest/spec/.*|(\\.|/)(test|spec))\\.js$',
testPathIgnorePatterns: [
'<rootDir>/node_modules'
],
transformIgnorePatterns: [
'/node_modules/'
]
};
So I've tried to look for similar cases around the web but in most cases the problems come from /node_modules or something missing in the jest config. But I can't find what's wrong in my case, would really appreciate any hints what can I try
up: someone suggested that I need to add babel-jest to my package.json but it's already in /node_modules - it is added with jest package
The problem surrounds the fact that you have no babel-loader setup so the project will blow up on import and export commands that do not get removed from the source code during compilation as babel has no idea how to handle that without babel-loader installed and configured.
For a quick example of how to get started with ES6 transpiling and module loading you can check out this example.
youtube.com/watch?v=X5wTsHRsbIA

VSCode typescript importing json file highlighting issue

I have some strange behaviour when importing json files using the import statement in typescript while using VSCode. Note this is not an issue with typescript itself just VSCode highlighting.
I have edited my tsconfig.json adding resolveJsonModule and esModuleInterop with the value of true to my compiler options to enable importing json within typescript.
Also I have added this package to my project
https://www.npmjs.com/package/json-d-ts
and added a typeRoots attribute to the tsconfig.json with a value of ["node_modules/json-d-ts"]
I've imported the json file (found at src/config/firebaseServiceKey.json) within a module (found at src/firebaseApp.ts) which is within a parent directory, thus the import looks like this:
import databaseUrl from "./config/firebaseDatabaseURL.json";
VSCode does not complain about this import:
However I have another module which imports the same file at a different level in the project directory, this module is found at test/utils.ts its import look like this:
import serviceKey from "../src/config/firebaseServiceKey.json";
This time VSCode does not seem to like the relative import and highlights the module as missing:
Any ideas how to fix configure VSCode to fix this problem?
Here is the relevant section of the result of running tsc --traceResolution:
======== Resolving module '../src/config/firebaseServiceKey.json' from '/home/jty/April2018/vs-server/test/utils.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'TypeScript'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.ts' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.tsx' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.d.ts' does not exist.
Directory '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' does not exist, skipping all lookups in it.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'JavaScript'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.js' does not exist.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json.jsx' does not exist.
Directory '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' does not exist, skipping all lookups in it.
Loading module as file / folder, candidate module location '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json', target file type 'Json'.
File '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json' exist - use it as a name resolution result.
======== Module name '../src/config/firebaseServiceKey.json' was successfully resolved to '/home/jty/April2018/vs-server/src/config/firebaseServiceKey.json'. ========
Here is my tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
}
},
"include": [
"src/**/*"
],
"typeRoots": [
"node_modules/json-d-ts"
]
}
I have faced similar issue, check your file is included as #Matt McCutchen said, the file which contains
import serviceKey from "../src/config/firebaseServiceKey.json";
should be included under src folder as you described in the tsconfig.json
"include": [
"src/**/*"
],
In my case, it was a test file which should not be included in the build. Because of that I have decided to ignore that highlight in the vs.
// #ts-ignore
import packageJson from '../../../../package.json';

Does Jest support ES6 import/export?

If I use import/export from ES6 then all my Jest tests fail with error:
Unexpected reserved word
I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an even simpler test case:
var Validation = require('../src/components/validation/validation'); // PASS
//import * as Validation from '../src/components/validation/validation' // FAIL
Same error. Obviously there's a problem with import/export here. It's not practical for me to rewrite my code using ES5 syntax just to make my test framework happy.
I have babel-jest. I tried various suggestions from GitHub issues. It is no go so far.
File package.json
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"jest": {
"testPathDirs": [
"__tests__"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
},
File babelrc
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators-legacy"]
}
Is there a fix for this?
From my answer to another question, this can be simpler:
The only requirement is to configure your test environment to Babel, and add the ECMAScript 6 transform plugin:
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
And that's it. Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.
UPDATE 2020 - native support of ECMAScript modules (ESM)
According to this issue, there is native support of ESM from jest#25.4.0. So you won't have to use babel anymore. At the time of writing this answer (05/2020), to activate that you need to do three simple things:
Make sure you don't transform away import statements by setting transform: {} in config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
So your Jest configuration file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
And to set --experimental-vm-modules flag, you will have to run Jest as follows:
node --experimental-vm-modules node_modules/jest/bin/jest.js
Also note in the Github issue that this approach does not yet support the jest object. So you may need to import it manually:
import {jest} from '#jest/globals'
(I hope this will change in the future)
For an updated configuration, I'm using https://babeljs.io/setup#installation
Select JEST and be happy:
As a reference, the current configuration:
npm install --save-dev babel-jest
In your package.json file, make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
Install babel preset:
npm install #babel/preset-env --save-dev
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Run your tests:
npm run test
In package.json, kindly set like this one: "test": "node --experimental-vm-modules node_modules/.bin/jest"
Should be good!
It's a matter of adding stage-0 to your .babelrc file. Here is an example:
{
"presets": ["es2015", "react", "stage-0"],
"plugins": ["transform-decorators-legacy"]
}
I encountered the same issue.
These are what I did:
yarn add --dev babel-jest #babel/core #babel/preset-env
Make file jest.config.js in rootDir.
module.exports = {
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
transform: {
'^.+\\.(js|jsx)?$': 'babel-jest'
},
testEnvironment: 'node',
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1'
},
testMatch: [
'<rootDir>/**/*.test.(js|jsx|ts|tsx)', '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
Then make file babal.config.js in rootDir.
Go like this:
module.exports = {
"presets": ["#babel/preset-env"]
}
Below is how I setup jest, typescript and ES Modules for my project.
jest.config.js
/**
* #type {import('ts-jest/dist/types').InitialOptionsTsJest}
* To configure ESM support, see: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
*
**/
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true
}
},
setupFiles: ['<rootDir>/__tests__/setup.ts'],
};
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"outDir": "./dist",
"moduleResolution": "node",
// "strict": true,
"esModuleInterop": true,
"inlineSourceMap": true,
}
}
package.json scripts and devDependencies
"scripts": {
"start": "node ./dist/server.js",
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
},
"devDependencies": {
"#jest/globals": "^27.4.4",
"#types/express": "^4.17.13",
"#types/jest": "^27.4.0",
"#types/supertest": "^2.0.11",
"cross-env": "^7.0.3",
"supertest": "^6.2.1",
"ts-jest": "^27.1.3"
}
__tests__/setup.ts
import dotenv from 'dotenv';
dotenv.config({
path: './.env.test'
});
all is explained in the jest docs: jest docs
1.
npm install --save-dev babel-jest #babel/core #babel/preset-env
in file: babel.config.js
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
In addition to installing babel-jest (which comes with Jest by default now) be sure to install regenerator-runtime.
To add support for React and react-testing-library it may be useful to eject CreateReactApp and take all needed Jest configuration from the package.json. It is ready to use with another bundler, Rollup in my case.