Как подключить jquery в visual studio code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Create folder : typings/jquery |
Save to this folder : https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/jquery/jquery.d.ts |
Add first line of file.js : /// |
source : http://stackoverflow.com/questions/29970278/visual-studio-code-jquery-suggestion |
If the light bulb doesn't appear, you can add the type definitions manually: |
Create typings\jquery folder structure within your project folder (if not exist)* |
Get latest jQuery type definitions file from GitHub |
Click "Raw" |
Ctrl + S (File > Save) |
Save it to your typings\jquery\ folder as jquery.d.ts |
Use it by. |
. either adding reference to the top of every source file (*.js) where you need it: |
/// |
. or adding reference in the files section of your jsconfig.json file (if exist) within your project root folder to use it in every source file: |
"files": [ |
"typings/jquery/jquery.d.ts" |
] |
> |
Done. |
*you can save the definitions file anywhere you want, but the suggested folder is that one what will be also created by VSCode for this. Just make sure to set the right refrence path (is wrong if underlined red ;-) ) |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
If you really just want to execute the steps without any explanation, try to jump right to the Conclusion section.
That being said, you can always read the parts that you are not sure about later :)
Prerequisites
Before going further, you will need node.js and npm . If you don’t know what those are, lets just say that npm is a package manager and it requires Node. We will use npm from within VS Code (in command line), to help us install our jQuery “IntelliSense” definition file.
Install Node and NPM and make sure the path is added to you PATH environment variable. This way, you will be able to get access to node and npm from everywhere without typing the file path every time. Which will become really useful really fast, I am telling you.
If I remember well, during the installation process, the installer will prompt you about that. But its been a while since I installed Node, so I might be wrong here.
After the installation, open a console ( cmd for Windows users) and type npm . If this does not work, look at the following link: fixing npm path in Windows 8. For other Windows versions this will be pretty similar. For other OS, I really don’t know - Google is your friend tho… sry
jQuery IntelliSense
The project directory
Now that Node.js and NPM are installed, lets create a Visual Studio Code folder . I created my project there at F:\Repos\BlogPost\jquery-intellisense .
In my index.html file I used the Bootstrap 3 Snippets extension to create the basic layout ( bs3-template:html5 snippet). I changed the linked jQuery file to the version 3.1.0 and I also included the integrity and crossorigin attributes to my script tag.
Here is the full index.html file:
jQuery TypeScript type definitions
Now, you might think the following:
Why is the title saying JavaScript but now you talk about TypeScript ?
We will use a TypeScript type definitions file in JavaScript.
If you don’t know TypeScript, this is also a nice topic to look into. But lets keep this for another day…
Installing TSD globally
Lets install the npm package named TSD globally, by typing the following command:
Open a console (a VS Code terminal, a cmd for Windows users, etc.), it doesn’t really matter since we are installing the package globally.
Installing the jQuery TypeScript type definitions file
Once this is done, open a new console (or use the same one), but this time, make sure that you are in your project folder .
Type the following command:
This will install the TypeScript type definitions file we are looking for.
Your project structure should now look like this:
Use the definition file(s)
Lets open our app.js file. If you type $ there is still nothing. To enable jQuery IntelliSense, we need to add a /// reference instruction to our JavaScript file.
For some reasons, VS Code does not update after you type the path so if you are stuck with an error like the following, reopen the file and it should fix it.
Here is the copyable snippet:
This basically told VS Code to append the type definitions contained in our tsd.d.ts file to its actual IntelliSense.
If you open the tsd.d.ts file you will see a reference to jquery/jquery.d.ts which is our jQuery type definitions file (the file we “installed” earlier). So, by linking the tsd.d.ts in our JavaScript files, it allows us to include all our loaded type definitions files at once (we only have jQuery for now, but who knows the future ;) ).
Back to our app.js file, we now have full jQuery IntelliSense:
What to do in your next project
Now that we have everything setup and working, the only thing you need to do in your next project is to Install the jQuery TypeScript type definitions file and reference it in your JavaScript files, as explained in the Use the definition file(s) section.
So the command you want to remember is this one:
Note that the value of the path attribute must match your tsd.d.ts file location, so you might need to adjust it.
Conclusion
It was pretty strait forward, assuming you already had Node.js and npm installed, we did the following:
Most of the blog postings are now outdated, as we finally have automatic type acquisition with version 1.8+ - you no longer need to install the typings yourself.
If you use npm and have a package.json in your project and jQuery is listed there, it should already work.
If you do not use npm, you can create the file jsconfig.json in the project root with the following content and you are good to go:
hi kwood, can i add jquery intellisense to vs code without a project? i edit many arbitrary js files in different environments.
This worked for me on one machine but not on another. (Same repo on both.) Any insight into what might prevent jquery support when it's manually included like this?
Type this command in your project root :
i tried installing it globally. It got added to the global modules but did not take effect in vs code. Any ideas ? (and yes i have tried closing and opening vs code after i installed it globally)
@eranotzap I believe this command has to be run in a project and not globally. When you install it globally it does not work.
I had the same problem and google brought me here. I added the type jsconfig.json and "typeAcquisition" and still nothing.
Turns out you have to have node and npm installed. Even if you are not using them for package management and are importing jquery from a CDN.
Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code's Automatic Type Acquisition will automatically install community maintained typings file for
Automatic type acquisition requires npmjs, the Node.js package manager, which is included with the Node.js runtime. In this image you can see IntelliSense, including the method signature, parameter info, and the method's documentation for the popular lodash library.
So vs code uses npm for auto type acquisition.
May be super basic, but it solved my problem so I hope it helps someone else too.
I also used the configuration in jsconfig.json as described by kwood. Not sure I needed to specify it manually after installin npm but it is working so i'm not asking questions
Visual Studio Code – популярный бесплатный редактор кода, созданный Microsoft’ом для программистов. VS Code никак не связан с Visual Studio. VS Code работает быстрее Атома, активно развивается и легко расширяется плагинами.
- отладчик кода
- встроенный терминал
- удобные инструменты для работы с Git
- подсветка синтаксиса для множества популярных языков и файловых форматов
- удобная навигация
- встроенный предпросмотр Markdown
- умное автодополнение
- встроенный пакетный менеджер
Пакетный менеджер нужен для установки и удаления пакетов расширений (плагинов). Для удобной разработки на JavaScript для бэкенда и фронтенда нужно установить несколько пакетов.
Для установки нового пакета зайдите во вкладку “Extensions” которая находится в выпадающем меню “View”, и введите название пакета в строке поиска, нажмите кнопку “Install”.
Babel и ES6
VS Code содержит понятие “сборки проекта”. Редактор можно настроить таким образом, чтобы сборка JavaScript-проекта заключалась в конвертации кода из ES6 в читаемый ES5 с Source Maps с помощью Babel.
Добавьте таск (задание) в файл tasks.json в директории .vscode в корне вашего проекта:
Теперь комбинация клавиш Shift+Ctrl+B (Windows/Linux) или Shift+CMD+B (macOS) запустит сборку.
Стандарты кодирования
Eslint – это утилита, проверяющая стандарты кодирования на JavaScript. Стандарт де-факто в мире JS.
Нужно сначала установить eslint в системе, а потом установить расширение VS Code, которое будет использовать установленный линтер. Есть разные способы интеграции линтера с расширением. Мы рассмотрим установку линтера глобально в системе.
- Установите Node.js, используя пакетный менеджер вашей операционной системы.
- Установите eslint командой npm install -g eslint . Вероятно, вам понадобится использовать sudo .
Установите плагины, которые конфигурируют eslint . Без них (по умолчанию) eslint ничего не проверяет.
eslint требует наличия конфигурационного файла. Создайте в корне вашего проекта файл .eslintrc.yml со следующим содержанием:
Автоматическое дополнение
VS Code содержит мощную систему анализа кода для автодополнений и подсказок – IntelliSense.
IntelliSense работает сразу, но для настройки деталей нужно создать конфигурационный файл jsconfig.json .
jsconfig.json
Если положить в корень директории с JavaScript-проектом конфигурационный файл jsconfig.json , то VS Code будет использовать эту конфигурацию для работы с вашим проектом. Вот пример такого файла:
Здесь можно настроить, например, какие директории стоит исключить из системы автодополнений IntelliSense. VS Code совместим с node, webpack, bower, ember и другими популярными инструментами. Полная документация по jsconfig доступна на сайте VS Code.
Отладка
VS Code содержит встроенный отладчик кода. Вы можете, например, отметить брейкпойнты (точки остановки) и следить за состоянием приложения в реальном времени.
Для отладки бэкенд-кода достаточно встроенных возможностей. Для отладки фронтенд-кода нужно установить плагин для соответствующего браузера:
Подробнее об отладке можно узнать на сайте VS Code.
Ссылки
Курс по настройке окружения для работы в современной экосистеме JavaScript.
This topic describes some of the advanced JavaScript features supported by Visual Studio Code. Using the TypeScript language service, VS Code can provide smart completions (IntelliSense) as well as type checking for JavaScript.
IntelliSense
Visual Studio Code's JavaScript IntelliSense provides intelligent code completion, parameter info, references search, and many other advanced language features. Our JavaScript IntelliSense is powered by the JavaScript language service developed by the TypeScript team. While IntelliSense should just work for most JavaScript projects without any configuration, you can make IntelliSense even more useful with JSDoc or by configuring a jsconfig.json project.
For the details of how JavaScript IntelliSense works, including being based on type inference, JSDoc annotations, TypeScript declarations, and mixing JavaScript and TypeScript projects, see the JavaScript language service documentation.
When type inference does not provide the desired information, type information may be provided explicitly with JSDoc annotations. This document describes the JSDoc annotations currently supported.
In addition to objects, methods, and properties, the JavaScript IntelliSense window also provides basic word completion for the symbols in your file.
Typings and Automatic Type Acquisition
IntelliSense for JavaScript libraries and frameworks is powered by TypeScript type declaration (typings) files. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience in a performant manner.
Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code's Automatic Type Acquisition will automatically install community maintained typings file for you.
Automatic type acquisition requires npmjs, the Node.js package manager, which is included with the Node.js runtime. In this image you can see IntelliSense, including the method signature, parameter info, and the method's documentation for the popular lodash library.
Type declaration files are automatically downloaded and managed by Visual Studio Code for packages listed in your project's package.json or that you import into a JavaScript file.
You can alternately explicitly list packages to acquire type declaration files for in a jsconfig.json.
Most common JavaScript libraries ship with declaration files or have type declaration files available. You can search for a library's type declaration file package using the TypeSearch site.
Fixing npm not installed warning for Automatic Type Acquisition
Automatic Type Acquisition uses npm, the Node.js package manager, to install and manage Type Declaration (typings) files. To ensure that Automatic Type Acquisition works properly, first ensure that you have npm installed on your machine.
Run npm --version from a terminal or command prompt to quickly check that npm is installed and available.
If you have npm installed but still see a warning message, you can explicitly tell VS Code where npm is installed with the typescript.npm setting. This should be set to the full path of the npm executable on your machine, and this does not have to match the version of npm you are using to manage packages in your workspace. typescript.npm requires TypeScript 2.3.4+.
For example, on Windows, you would add a path like this to your settings.json file:
JavaScript projects (jsconfig.json)
The presence of a jsconfig.json file in a directory indicates that the directory is the root of a JavaScript project. jsconfig.json specifies the root files and the options for the language features provided by the JavaScript language service. For common setups, a jsconfig.json file is not required, however, there are situations when you will want to add a jsconfig.json .
- Not all files should be in your JavaScript project (for example, you want to exclude some files from showing IntelliSense). This situation is common with front-end and back-end code.
- Your workspace contains more than one project context. In this situation, you should add a jsconfig.json file at the root folder for each project.
- You are using the TypeScript compiler to down-level compile JavaScript source code.
Location of jsconfig.json
To define our code as a JavaScript project, create jsconfig.json at the root of your JavaScript code as shown below. A JavaScript project is the source files of the project and should not include the derived or packaged files (such as a dist directory).
In more complex projects, you may have more than one jsconfig.json file defined inside a workspace. You will want to do this so that the source code in one project does not appear in the IntelliSense of another project.
Illustrated below is a project with a client and server folder, showing two separate JavaScript projects:
Writing jsconfig.json
Below is a simple template for jsconfig.json file, which defines the JavaScript target to be ES6 and the exclude attribute excludes the node_modules folder. You can copy and paste this code into your jsconfig.json file.
The exclude attribute tells the language service which files are not part of your source code. If IntelliSense is slow, add folders to your exclude list (VS Code will prompt you to do this if it detects slow completions). You will want to exclude files generated by a build process (such as a dist directory). These files will cause suggestions to show up twice and will slow down IntelliSense.
You can explicitly set the files in your project using the include attribute. If no include attribute is present, then this defaults to including all files in the containing directory and subdirectories. When a include attribute is specified, only those files are included.
Here is an example with an explicit include attribute:
The best practice, and least error prone route, is to use the include attribute with a single src folder. Note that file paths in exclude and include are relative to the location of jsconfig.json .
For more information, see the full jsconfig.json documentation.
Migrating to TypeScript
It is possible to have mixed TypeScript and JavaScript projects. To start migrating to TypeScript, rename your jsconfig.json file to tsconfig.json and set the allowJs property to true . For more information, see Migrating from JavaScript.
Note: jsconfig.json is the same as a tsconfig.json file, only with allowJs set to true. See the documentation for tsconfig.json here to see other available options.
Type checking JavaScript
VS Code allows you to leverage some of TypeScript's advanced type checking and error reporting functionality in regular JavaScript files. This is a great way to catch common programming mistakes. These type checks also enable some exciting Quick Fixes for JavaScript, including Add missing import and Add missing property.
TypeScript can infer types in .js files same as in .ts files. When types cannot be inferred, they can be specified using JSDoc comments. You can read more about how TypeScript uses JSDoc for JavaScript type checking in Type Checking JavaScript Files.
Type checking of JavaScript is optional and opt-in. Existing JavaScript validation tools such as ESLint can be used alongside the new built-in type checking functionality.
You can get started with type checking a few different ways depending on your needs.
Per file
The easiest way to enable type checking in a JavaScript file is by adding // @ts-check to the top of a file.
Using // @ts-check is a good approach if you just want to try type checking in a few files but not yet enable it for an entire codebase.
Using a setting
To enable type checking for all JavaScript files without changing any code, just add "js/ts.implicitProjectConfig.checkJs": true to your workspace or user settings. This enables type checking for any JavaScript file that is not part of a jsconfig.json or tsconfig.json project.
You can opt individual files out of type checking with a // @ts-nocheck comment at the top of the file:
You can also disable individual errors in a JavaScript file using a // @ts-ignore comment on the line before the error:
Using jsconfig or tsconfig
To enable type checking for JavaScript files that are part of a jsconfig.json or tsconfig.json , add "checkJs": true to the project's compiler options:
This enables type checking for all JavaScript files in the project. You can use // @ts-nocheck to disable type checking per file.
JavaScript type checking requires TypeScript 2.3. If you are unsure what version of TypeScript is currently active in your workspace, run the TypeScript: Select TypeScript Version command to check. You must have a .js/.ts file open in the editor to run this command. If you open a TypeScript file, the version appears in the lower right corner.
Global variables and type checking
Let's say that you are working in legacy JavaScript code that uses global variables or non-standard DOM APIs:
If you try to use // @ts-check with the above code, you'll see a number of errors about the use of global variables:
- Line 2 - Property 'webkitNotifications' does not exist on type 'Window'.
- Line 2 - Cannot find name 'CAN_NOTIFY'.
- Line 3 - Property 'webkitNotifications' does not exist on type 'Window'.
If you want to continue using // @ts-check but are confident that these are not actual issues with your application, you have to let TypeScript know about these global variables.
To start, create a jsconfig.json at the root of your project:
Then reload VS Code to make sure the change is applied. The presence of a jsconfig.json lets TypeScript know that your Javascript files are part of a larger project.
Now create a globals.d.ts file somewhere your workspace:
d.ts files are type declarations. In this case, globals.d.ts lets TypeScript know that a global CAN_NOTIFY exists and that a webkitNotifications property exists on window . You can read more about writing d.ts in the TypeScript documentation. d.ts files do not change how JavaScript is evaluated, they are used only for providing better JavaScript language support.
Using tasks
Using the TypeScript compiler
One of the key features of TypeScript is the ability to use the latest JavaScript language features, and emit code that can execute in JavaScript runtimes that don't yet understand those newer features. With JavaScript using the same language service, it too can now take advantage of this same feature.
The TypeScript compiler tsc can down-level compile JavaScript files from ES6 to another language level. Configure the jsconfig.json with the desired options and then use the –p argument to make tsc use your jsconfig.json file, for example tsc -p jsconfig.json to down-level compile.
Read more about the compiler options for down level compilation in the jsconfig documentation.
Running Babel
The Babel transpiler turns ES6 files into readable ES5 JavaScript with Source Maps. You can easily integrate Babel into your workflow by adding the configuration below to your tasks.json file (located under the workspace's .vscode folder). The group setting makes this task the default Task: Run Build Task gesture. isBackground tells VS Code to keep running this task in the background. To learn more, go to Tasks.
Once you have added this, you can start Babel with the ⇧⌘B (Windows, Linux Ctrl+Shift+B ) (Run Build Task) command and it will compile all files from the src directory into the lib directory.
Tip: For help with Babel CLI, see the instructions in Using Babel. The example above uses the CLI option.
Disable JavaScript support
If you prefer to use JavaScript language features supported by other JavaScript language tools such as Flow, you can disable VS Code's built-in JavaScript support. You do this by disabling the built-in TypeScript language extension TypeScript and JavaScript Language Features (vscode.typescript-language-features) which also provides the JavaScript language support.
To disable JavaScript/TypeScript support, go to the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and filter on built-in extensions (Show Built-in Extensions in the . More Actions dropdown), then type 'typescript'. Select the TypeScript and JavaScript Language Features extension and press the Disable button. VS Code built-in extensions cannot be uninstalled, only disabled, and can be re-enabled at any time.
Partial IntelliSense mode
VS Code tries to provide project-wide IntelliSense for JavaScript and TypeScript, which is what makes features such as auto-imports and Go to Definition possible. However, there are some cases where VS Code is limited to working only with your currently opened files and is unable to load the other files that make up your JavaScript or TypeScript project.
This can happen in a few instances:
- You are working with JavaScript or TypeScript code on vscode.dev or github.dev and VS Code is running in the browser.
- You open a file from a virtual file system (such as when using the GitHub Repositories extension).
- The project is currently loading. Once loading completes, you will start getting project-wide IntelliSense for it.
In these cases, VS Code's IntelliSense will operate in partial mode. Partial mode tries its best to provide IntelliSense for any JavaScript or TypeScript files you have open, but is limited and is not able to offer any cross-file IntelliSense features.
Which features are impacted?
Here's an incomplete list of features that are either disabled or have more limited functionality in partial mode:
- All opened files are treated as part of a single project.
- Configuration options from your jsconfig or tsconfig (such as target ) are not respected.
- Only syntax errors are reported. Semantic errors — such as accessing an unknown property or passing the wrong type to a function — are not reported.
- Quick Fixes for semantic errors are disabled.
- Symbols can only be resolved within the current file. Any symbols imported from other files will be treated as being of the any type.
- Commands such as Go to Definition and Find All References will only work for opened files instead of across the entire project. This also means that symbol from any packages you install under node_module will not be resolved.
- Workspace symbol search will only include symbols from currently opened files.
- Auto imports are disabled.
- Renaming is disabled.
- Many refactorings are disabled.
Some additional features are disabled on vscode.dev and github.dev :
Checking if you are in partial mode
To check if the current file is using partial mode IntelliSense instead of project-wide IntelliSense, hover over the JavaScript or TypeScript language status item in the status bar:
The status item will show Partial mode if the current file is in partial mode.
Читайте также: