Using chrome extension apis in typescript - javascript

I'm building a chrome extension written in TypeScript. I'm using WebStorm and I added the chrome-DefiniteltyTyped library in my project.
However, when I write this in my typescript code : chrome.extension.getURL
I got an error : cannot find name 'chrome'.
Because of this, my javascript file is not generated and I cannot use it in my extension.
Do you guys have any solution?

As of typescript 2 (or 2.x, not sure), you should import the chrome types from #types.
in package.json:
"devDependencies": {
...
"#types/chrome": "0.0.35", // or just npm install --save-dev #types/chrome
And in tsconfig:
"types": [
//(various types, e.g. jquery, core-js),
"chrome"
]

That should work fine : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/chrome/index.d.ts
TIP: make sure you have a reference tag added:
/// <reference path="pathTo/chrome.d.ts"/>

Types Across Chrome and Firefox
Since the extension API is basically the same across Chrome and Firefox now, you can use #types/chrome for both situations.
1. install
yarn add #types/chrome --dev
2. update tsconfig
{
"compilerOptions": {
....
"types": ["chrome"]
}
}
3. Get browser api function
export function getBrowserInstance(): typeof chrome {
// Get extension api Chrome or Firefox
const browserInstance = window.chrome || (window as any)['browser'];
return browserInstance;
}

You just need to install Type definition to make it work, let's install it:
yarn add #types/chrome --dev
or NPM
npm install #types/chrome --save-dev
now use free of error!

I just ran into the below error when trying to develop a Chrome extension using TypeScript in VS Code and all I had to do was simply run:
npm install --save-dev #types/chrome
This will enter "#types/chrome": "0.0.120" under "devDependencies" in your package.json file.
Fixed error:
[tsl] ERROR in C:\Users\my_user\Documents\my_chrome_extension\src\content.ts(28,3)
TS2304: Cannot find name 'chrome'.

What did work:
Have typescript ignore the offending code by adding a comment like this above it.
// #ts-ignore: saying 'chrome' is not found
What didn't work:
I had #types/chrome installed when I ran into this issue.
In the tsconfig.json, adding "chrome" under types and specifying the
typesroot.
Adding a reference path comment and all sorts of ways to
import "chrome".
try these before you add the #ts-ignore comment.
Background:
I am working on a chrome extension using Angular 11. I need to access chrome.runtime.sendMessage to send information to a background worker.

Make sure you have #types/chrome installed. I don't think you need to update the types and the typeroots of tsconfig. Then use the type definitions from chrome by accessing the chrome type which will be globally available, for example:
type getUrl = typeof chrome.runtime.getURL;
A bit more context in this GitHub issue

Related

the syntax requires an imported helper named __spreadArrays

When I'm trying to use spreading in typescript like:
.reduce((unique, x) => {
unique.some(element => element.machineName === x.machineName) ? unique : [...unique, x];
}
I get warning with red marking from Visual Studio Code:
the syntax requires an imported helper named __spreadArrays
typescript version: "2.3.4"
target: "es5"
I think in later versions this issue is fixed, but right now I can't migrate. How can I fix it?
Note: Project gets compiled fine and works. But red underlying in VS Code in annoying.
In my case the problem it was target: "es5" in compilerOptions at tsconfig.json.
So I change it to es6 to get it works without adding dependency.
Quick fix, short answer
npm install tslib#latest --save
Update
I got this issue again (now with tslib version 2.2.0) after updating VS Code, again updating fixed the issue.
Original
I had this issue with tslib version 1.14.1
npm update tslib --save didn't really do anything
npm install tslib#latest --save did the job, it updated to version 2.2.0
For VS Code the notification is based on the tsLib exports.
Actually nothing bad happens without doing anything, it is just lack of typing.
Solution: Update tsLib dependency to get rid of the highlighting. In my case it was version 1.9.0. Update to 1.10.0 solved the issue.
__spreadArrays is added in 1.10.0 tsLib version:
https://github.com/microsoft/tslib/blob/1.10.0/tslib.es6.js
Update: Since some time passed, it is better to update version to 2.2.0 (based on last comments) or the latest.
Assuming your tslib is installed correctly and up to date, you might still get this error in VS Code if the editor is using a different Typescript version.
(taken from zok's answer on this SO question)
Open Command Palette (Cmd+Shift+P on Mac. Focused file must be .ts or .tsx otherwise it won't show the option to change version)
Select "TypeScript: Select TypeScript Version..."
It shows VSCode's TS version and Workspace's (project) one, pick the workspace one
This error might happen if you have in your tsconfig.json file :
{
"importHelpers": true,
"target": "es5"
}
If for any reason you can't upgrade to es6, setting importHelpers to false will make the error go away ...
for yarn users: yarn upgrade tslib#latest
from right side down
hover on curly braces beside of TypeScript and then click on version
it will give you few options, generally related to project
just select version and it will work fine
you may need to upgrade to tslib#2.2.0
Just make sure tslint is enabled in the bottom of vscode editor options
Ran into this issue with a dependency and resolved it by updating its tsconfig.ts with the path to the top level lastest tslib.
"importHelpers": true,
"paths": {
"tslib": [ "../tslib/tslib.d.ts" ]
}

Bootstrap v4 runtime/load error in Aurelia

I have the following in my aurelia.json file, among the rest of what you'd usually find. I copied it directly from the reference implementation, and as you'd therefore expect, it works fine.
{
'build': {
'bundles': [
'name': 'vendor-bundle.js'
'dependencies': [
"jquery",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist",
"main": "js/bootstrap.min",
"deps": ["jquery"],
"exports": "$",
"resources": [
"css/bootstrap.css"
]
}
]
]
}
}
However, I'm trying to migrate to Bootstrap 4, and it just doesn't seem to be working. In order to update the package, I've tried changing build.bundles.dependencies[].path to ../jspm_packages/github/twbs/bootstrap#4.0.0-beta as well as to ../node_modules/bootstrap-v4-dev/dist, but it doesn't change the error code or make the error manifest any less. I've also tried copying the v4 files into the dist folder for v3, which also causes the same problem.
Build is always clean; the error occurs at run-time:
DEBUG [templating] importing resources for app.html
Uncaught TypeError: plugin.load is not a function
Unhandled rejection Error: Failed loading required CSS file: bootstrap/css/bootstrap.css
EDIT:
Thanks to Ashley Grant's answer, I have updated Bootstrap through NPM, obviating any changes to aurelia.json. The error remains unchanged, which would seem to indicate a bug were it not for the fact that other people have successfully performed this migration without errors using the same toolchain.
EDIT2:
I've created steps to reproduce the bug:
$ au new
name # can be any valid value
2 # Selects TypeScript as the language
1 # Create project structure
1 # Install dependencies
cd into the project directory.
Add the two entries listed above to build.bundles[1].dependencies in aurelia_project/aurelia.json
$ npm install jquery --save
$ npm install bootstrap#^4.0.0-beta --save
Change src/app.html to the following:
<template>
<require from="bootstrap/css/bootstrap.css"></require>
</template>
Finally, execute either of the following and browse to the provided URL.
$ au run
OR
$ au build
$ serve
This yields the errors described in both Google Chrome Version 55.0.2883.87 (64-bit) and Mozilla Firefox 55.0.3 on my Arch Linux systems. I've not yet had the opportunity to test it on other systems.
Edit3:
Thanks to #vidriduch, everything appears to be working. However, if you look at the console, you find the following:
Uncaught SyntaxError: Unexpected token export
vendor-bundle.js:3927Uncaught Error: Mismatched anonymous define() module: [entirety of vendor-bundle.js printed here]
These are the two very first messages when the page loads in debug mode, but no other errors arise.
You are missing popper.js dependency for Bootstrap 4.0.0-beta.
In order for Aurelia to accept this add
"node_modules/popper.js/dist/umd/popper.js"
on the top (as per comment from #hxtk) of prepend part of aurelia.json (assuming that you are using RequireJS, otherwise have a look at webpack dependency linking for Bootstrap https://getbootstrap.com/docs/4.0/getting-started/webpack/)
Just to mention, the version of popper.js you need to install is 1.11.0 (https://github.com/twbs/bootstrap/issues/23381), so
npm install popper.js#1.11.0
or
yarn add popper.js#1.11.0
and it should work :)
Your aurelia.json configuration is correct. I'm going to guess you never ran npm install bootstrap#^4.0.0-beta --save as you are mentioning copying files in to a versioned node_modules folder, and NPM doesn't use versioned folders like JSPM does.
So run npm install bootstrap#^4.0.0-beta --save and things should start working. I have your exact configuration working in an application for one of my clients.

Prevent "test/expect/etc is not defined" errors when using Jest

Facebook's Jest testing framework is easy to get started with, but the documentation overlooks an annoying aspect: test statements will be highlighted as errors by any editor that tries to warn of undefined symbols, because test, expect, and all matcher methods are not defined.
Similary, attempting to run a test file with node directly will fail with ReferenceError: test is not defined.
What require/import statement(s) need to be added for those errors to go away?
Node
If you want to run them directly through node, try to require jest and/or jest-runtime. Also give #types/jest a try as well.
Check Edit 2 for new info about this
Edit
#types/jest (jest-DefinitelyTyped) is definitely needed (or just one solution). If you install it (e.g., dev dependency), the IDE errors should go away.
I just tried it on Webstorm, and it works.
Edit 2
The new Jest#20 Matchers (e.g., .resolves and .rejects) are still not defined in #types/jest. You can keep track of its status on the links below:
https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16645
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16803
It should be available soon, though!
Also, it doesn't seem possible to run it directly through node. Last night I tried a bunch of different things, but using jest is the way to go - it really uses node under the hood, so I thought it would be possible as well. #thymikee over your opened issue at GitHub made clear that it's not.
Edit 3
The new release (20.0.1) includes the newest Jest definitions.
Lint
this isn't in the scope of this specific problem, but it also helps
Are you using something like ESLint? If so, you'll need eslint-plugin-jest
Following the steps described in this page: https://www.npmjs.com/package/eslint-plugin-jest, you will basically need to add it as an ESLint plugin and set jest globals in the ESLint configuration:
{
"env": {
"jest/globals": true
}
}
If you plan on supporting ES6 tests, you'll also need Babel and babel-jest plugin with the following jest configuration:
"transform": {
"^.+\\.js$": "babel-jest"
}
Finally, for Typescript tests you'd need the #types/jest and ts-jest packages as well
Adding following .eslintrc configuration is enough
{"env":
{
"jest": true
}
}
I'm using VSCode and ESLint, you need to install eslint-plugin-jest
Add jest info to your .eslintrc.js
{
"plugins": ["jest"]
},
"env": {
"jest/globals": true
}

How to create aurelia typescript project with vs2017rc

I am new to aurelia, and I need create a prototype project of the framework. At the beginning, I planed to use skeleton-typescript-aspnetcore skeleton, but when I tried the vs2017rc, I found it uses .csproj as the default format(while vs2015 is project.json/.xproj), I think we should follow the vs2017 because we will upgrade our IDE after it's been launched.
The vs2017 have a wizard to upgrade .xproj project, but after the upgrading(skeleton-typescript-aspnetcore), there still lots of error ahead me...
I also tried aurelia-cli, but seems it has not support vs2017 yet, does anyone could give a guide to create the prototype project? I will integrate some plugins like the skeleton mentioned above, such as gulp,karma,breeze...
thank you in advance.
Since Visual Studio 2017 just launched I thought I'd answer how I solved this, as there are still many errors when using "skeleton-typescript-aspnetcore".
Using https://github.com/aurelia/skeleton-navigation/releases/tag/1.1.2 as a starting point, these are the steps to get it running:
When you first run the project you will get errors complaining that some files located in /test/ is not under 'rootDir'. In your tsconfig.json the rootDir is defined as "src/", this can be solved simply by moving your test folder inside your src folder. This will cause new errors because the paths defined in those files has now changed. You will need to edit app, child-router and users imports like this:
import {Users} from '../../users'; IntelliSense should help you out here.
The command gulp test will also not run before changing to the new path, you can change the path in karma.conf.js:
files: [
'src/test/unit/setup.ts',
'src/test/unit/*.ts'
],
Next the file users.ts will throw errors like Type 'Response' is not assignable to type 'any[]'. You will need to tell TypeScript what you're declaring like this: public users : Object = []; or simply: public users = {};
The final problem is that you're going to have a lot of duplicate identifier errors, at the time of writing this the cause of this seems to be from the changes brought on by TypeScript version 2.2.1. I don't know what specifically breaks, but I know that previous version 2.1.5 still works. So what you need to do is to run npm install typescript#2.1.5 --save in your src/skeleton directory, the --save is just to update your package.json file, you can do this on your own later as well if you wish.
After you've done that your gulp errors (20~ of them) should be resolved. But there are still some errors remaining caused by duplicate signatures. Again, things have changed in TypeScript 2.0+, there is now a simplified way of getting and using declaration files. Here is an answer on SO on how to use the #types feature: How should I use #types with TypeScript 2 , but to keep this short and sweet you will have to go to your tsconfig.json file and explicitly tell where to find the #types/node folder. It would look something like this:
"compilerOptions": {
...
"typeRoots": [
"node_modules/#types"
],
"types": [ "node" ]
...
},
Hope this helps, with these changes the project should now build and launch correctly.
EDIT:
I recently ran into some problems again with building my project. I got a lot of duplicate identifiers again... I however ran across this answer on SO: TypeScript throws multiple duplicate identifiers
Apparently TypeScript latest ships with fetch definitions out of the box, so I was able to run the command from the answer in the link:
npm uninstall #types/whatwg-fetch
And upgrading from typescript 2.1.5 to latest:
npm install typescript --save
You might even want to install typescript globally by appending -g.
Also this will continue to be an issue unless you comment out/delete url and whatwg-fetch from typings.json globalDependencies in order to prevent it from recreating itself:
"globalDependencies": {
//"url": "github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
//"whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
}
Then you can either delete the typings folder, running typings install again or edit index.d.ts in the typings folder and delete the reference paths to whatwg-fetch and url.
Hope this helps someone who might've encountered the same problems even after "fixing" it.

how to add react jsx as javascript file type in vim and enable eslinting, auto completions?

I have recently started using vim.I want to set up files having .jsx extension to be treated as .js java script file in Vim.
Also I want to enable es-linting, snippets with my .jsx files. I have installed following packages in my system
npm install -g eslint
npm install -g babel-eslint
npm install -g eslint-plugin-react
I have also installed Bundle 'mxw/vim-jsx' to support jsx in vim.
Also added following lines in my .vimrc file
let g:syntastic_javascript_checkers = ['eslint']
let g:jsx_ext_required = 0
Edit
Found this vim plugin for react snippets:
Vim-react-snippets
I decided to write this tutorial to setup vim for React development in depth so that beginners find this useful when they start with vim and react.
Syntax highlighting
To get the jsx syntax high-lighting to look right in vim, use mxw's Vim JSX plugin.
Steps to Install mxw/vim-jsx Plugin
If you use Vundle,
add following lines in your .vimrc:
Plugin 'mxw/vim-jsx'
Plugin 'pangloss/vim-javascript'
This plugin depends upon pangloss/vim-javascript so you need to install that as well.
To install from within vim, use the commands below.
:so ~/.vimrc
To source changed .vimrc configuration file and use it, next
:PluginInstall
If you use pathogen
cd ~/.vim/bundle
git clone https://github.com/mxw/vim-jsx.git
Enable JSX Syntax Highlighing in javascript files
Add following lines in your .vimrc:
let g:jsx_ext_required = 0
Enabling eslint in vim
You need to install following helper npm packages along with latest eslint ( used 2.11.1 at the time of writing ).
Also make sure that you have node.js version 4 or above installed in your system.
babel-eslint - To support ES6 linting
eslint-plugin-react - React specific linting rules for ESLint
e.g prevent usage of setState in componentDidMount
npm install --save-dev eslint
npm install --save-dev babel-eslint
npm install --save-dev eslint-plugin-react
I decided to use common practices and conventions used by AirBnB, so I installed following packages as well. But You don't need them
If you do not want to use AirBnB eslint presets.
npm install --save-dev eslint-config-airbnb
npm install --save-dev eslint-plugin-import
npm install --save-dev eslint-plugin-jsx-a11y
Create a config file .eslintrc.json in your project's root:
(You can use eslint to generate eslint configuration file in intreactive way)
eslint --init
(If you chose any presets make sure you also install required package for that lint preset)
I extended "airbnb" but overrided some of rules for my project. You can use
"extends": "eslint:recommended" to enable some common lint rule recommended by eslint
Here is my .eslintrc.json file
{
"extends" : "airbnb",
"parser" : "babel-eslint",
"parserOptions" : {
"ecmaVersion" : 6,
"sourceType" : "module",
"ecmaFeatures" : {
"jsx":true
}
},
"env": {
"browser" : true,
"node" : true,
"jquery" : true
},
"settings":{
"react":{
"pragma":"React",
"version":"15.1.0"
},
"ecmascript":6,
"jsx":true
},
"plugins": [
"react"
],
"rules": {
"strict": 0,
"quotes": 0,
"no-unused-vars": 1,
"camelcase": 1,
"no-underscore-dangle": 1,
"comma-dangle":[1,"never"],
"indent":["error",4],
"react/jsx-indent":0,
"react/jsx-equals-spacing": [2, "always"],
"no-console":0,
"max-len":1,
"no-param-reassign":1,
"key-spacing": [
2,
{
"align": "colon",
"beforeColon": true,
"afterColon": true
}
],
"no-multi-spaces": [
2,
{
"exceptions":{
"VariableDeclarator":true,
"ImportDeclaration":true,
"JSXAttribute":true,
"AssignmentExpression":true
}
}
]
}
}
Now integrate ESLint with Syntastic Plugin in Vim
I decided to use Syntastic with vim for syntax error checking.
let g:syntastic_javascript_checkers = ['eslint']
All set but still there is one issue remaining with Syntastic.
Syntastic searches global node_modules instead of local project.
One solution will be install all packages eslint, babel-eslint etc globally which definately will not be a good practice.
Another solution is
Define a npm script in your package.json
"eslint": "eslint -c .eslintrc.json"
It will add all the locally installed npm packages in current path, so they will be available for execution.
And in your .vimrc file add
let g:syntastic_javascript_eslint_exe = 'npm run eslint --'
Here we are invoking linting via npm script from vim.
Alternative: use Plug 'mtscout6/syntastic-local-eslint.vim' plugin
Open error window in vim as you open your file -
Add following lines to your .vimrc to show current lint error (in case any) as you open your file for edit
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
Snipptes and auto-completion
There are different forks of snippet engines which allow the user to insert snippets by typing the name of a snippet hitting the expansion mapping.
github.com/SirVer/ultisnips:
python, supports all snippets in this repo.
github.com/garbas/vim-snipmate:
VimL, snipmate-snippets, engine sometimes behaves strange. Supports snippets/*
github.com/Shougo/neosnippet:
VimL, supports snippets/* with some configuration.
github.com/drmingdrmer/xptemplate: Totally different syntax, does not read snippets contained in this file, but it is also very powerful.
I prefer neosnippet. Install it in your vim, to enable snippets with neocomplete for auto-completion.
Neocomplete is an amazing autocomplete plugin with additional support for snippets. It can complete simulatiously from the dictionary, buffer, omnicomplete and snippets. This is the one true plugin that brings Vim autocomplete on par with the best editors.
See install instructions here for neocomplete
After installing above plugins you need to install one more plugin to enable react specific snippets
Bundle 'justinj/vim-react-snippets'
See install instructions here for that plugin.
If all setup done correctly, you have enabled vim with eslinting, auto completions, JSX syntax hightlighting for React, with ES6 features !
Taken from my blog post.
That plugin you installed already sets the filetype of .jsx files to javascript.jsx so those files should be treated as if their filetype was javascript plus any jsx-related feature provided by that plugin.
I have no idea how to set up Syntastic for jsx, but you can get linting without installing such a huge plugin. For that you will need to add the lines below to after/ftplugin/jsx.vim to tell Vim to automatically run eslint after a write:
" see :help 'errorformat'
setlocal errorformat=%E%f:\ line\ %l\\,\ col\ %c\\,\ Error\ -\ %m,%-G%.%#,%W%f:\ line\ %l\\,\ col\ %c\\,\ Warning\ -\ %m,%-G%.%#
" see :help 'makeprg' and $ eslint --help
setlocal makeprg=eslint\ -f\ compact
" run :make % on write
autocmd! BufWritePost <buffer> silent make % | silent redraw!

Categories

Resources