Tsc init не работает

tsc не распознает параметр ‘—init’

По какой-то причине npx tsc —init выводит следующую ошибку:

Я установил пакет typescript с Yarn 2 :

Может кто-нибудь объяснить мне, почему tsc не распознает —init и что я делаю не так?

ОБНОВЛЕНИЕ :

Как выяснил Дэниел, проблема в том, что npx не находит и не распознает пакет typescript , установленный с Yarn 2 . Решением было использовать вместо этого yarn : yarn tsc —init

2 ответа

Судя по выходным данным npx tsc —init , похоже, у вас нет установленного пакета typescript в каталоге, в котором вы запустили команду. npx пытается помочь, устанавливая все пакеты, необходимые для выполнения команды.

Несмотря на то, что он пытался быть полезным, в итоге не удалось установить пакет, который можно было бы ожидать в 2020 году. Если вы запустите $ npx tsc -v , вы, скорее всего, получите следующий результат:

Однако, если бы у вас был установлен пакет typescript , вы бы получили следующее:

Как видите, версия, установленная npm , отличается. Это потому, что npx закончил установку пакета tsc , а не typescript . Пакет tsc также предоставляет команду tsc . npx выбрал его вместо typescript , потому что, хотя оба пакета предоставляют команду tsc , она также называется tsc . npx подумал, что это больше подходит.

ОБНОВЛЕНИЕ:

Пряжа 2 представляет функцию Plug’n’Play . Зависимости устанавливаются совсем не так, как раньше в Yarn 1 и npm .

Пряжа 1 и npm помещают код для ваших пакетов в каталог node_modules в каждом отдельном проекте. npx идет искать там команды.

Yarn 2, с другой стороны, устанавливает код пакета в общую папку и помещает в ваш проект один файл .pnp.js , который выполняет сопоставление. Если вы устанавливаете пакет для одного проекта, вам не придется загружать его снова, если вы используете его в другом проекте.

Однако любой инструмент, который зависел от node_modules , будет сломан. Вот почему npx не смог найти typescript в вашем проекте. npx не знает о Plug’n’Play .

Подробнее об этой функции можно прочитать здесь: https://yarnpkg.com/features/pnp

Сюда пришли другие, которые не используют пряжу или npx, в моем случае это решает:

Источник

tsc does not recognize ‘—init’ option

For some reason npx tsc —init prints out the following error:

I have installed the typescript package with Yarn 2:

Can someone explain to me why tsc does not recognize —init and what i am doing wrong?

UPDATE:

As Daniel figured out, the problem is that npx does not find or recognize the typescript package installed with Yarn 2. The solution was to use yarn instead: yarn tsc —init

2 Answers 2

Judging from the output of npx tsc —init you do not seem to have the typescript package installed in the directory where you’ve run the command. npx tries to be helpful by installing any packages needed in order for the command to run.

Although it was trying to be helpful it ended up not installing the package one would expect in 2020. If you run $ npx tsc -v you will most likely get this output:

If you had the typescript package installed, however, you would have gotten this, instead:

Читайте также:  Disable скайрим не работает команда

As you can see, the version installed by npm is different. That’s because npx ended up installing the tsc package and not typescript . The tsc package also provides a tsc command. npx chose it instead of typescript because, while both packages provide a tsc command, it is also called tsc . npx thought it was a better fit.

UPDATE:

Yarn 2 introduces the Plug’n’Play feature. Dependencies are installed very differently from how Yarn 1 and npm used to.

Yarn 1 and npm place the code for your packages in the node_modules directory in every single project. npx goes to look for commands there.

Yarn 2, on the other hand, installs package code in a shared location and places in your project a single .pnp.js file that performs the mapping. If you install a package for one project, you won’t have to download it again if you use it in another project.

Any tooling that was dependent on node_modules , however, will be broken. That’s why npx was unable to find typescript in your project. npx does not know about Plug’n’Play .

Источник

‘tsc command not found’ in compiling typescript

I want to install typescript, so I used the following command:

and test tsc —version , but it just show ‘tsc command not found’. I have tried many ways as suggested in stackoverflow, github and other sites. but it doesn’t work. How could I know typescript is installed and where it is.

my OS is Unix, OS X El Capitan 10.11.6, node version is 4.4.3, npm version is 3.10.5

21 Answers 21

A few tips in order

  • restart the terminal
  • restart the machine
  • reinstall nodejs + then run npm install typescript -g

If it still doesn’t work run npm config get prefix to see where npm install -g is putting files (append bin to the output) and make sure that they are in the path (the node js setup does this. Maybe you forgot to tick that option).

I had to do this:

You are all messing with the global installations and -path files. Just a little error might damage every project you have ever written, and you will spend the rest of the night trying to get a console.log(‘hi’) to work again.

If you have run npm i typescript —save-dev in your project — just try to run:

And see if it works before messing with global stuff (unless of course you really know what you are doing)

After finding all solutions for this small issue for macOS only.
Finally, I got my TSC works on my MacBook pro.

This might be the best solution I found out.

For all macOS users, instead of installing TypeScript using NPM, you can install TypeScript using homebrew.

Please see attached screencap for reference.

If your TSC command is not found in MacOS after proper installation of TypeScript (using the following command: $ sudo npm install -g typescript , then ensure Node /bin path is added to the PATH variable in .bash_profile .

Open .bash_profile using terminal: $ open

Edit/Verify bash profile to include the following line (using your favorite text editor):

Load the latest bash profile using terminal: source

Lastly, try the command: $ tsc —version .

Easy fix for Mac I found. Just run these commands:

Nothing worked except this for me.

I had this same problem on Ubuntu 19.10 LTS.

Читайте также:  Видеокамера не работает инфракрасная подсветка

To solve this I ran the following command:

After that, I was able to use tsc .

This answer is specific for iTermV2 on MAC

First of all, I needed to instal as sudo (admin) during NPM install

sudo npm install -g typescript

NPM installs the libraries under /usr/local/Cellar/node/ /lib/node_modules/typescript folder and symlinks at /usr/local/Cellar/node/ /bin/tsc

/.zshrc ( .bashrc, if you use bash)and added /usr/local/Cellar/node/ /bin to the $PATH.

    reload the shell profile via source

/.zshrc (.bashrc in your case)

Globally installing TypeScript package worked for me.

The only solution that work for me was put npx tsc -v or for the compiling npx tsc salida.ts

«salida.ts» is the name of the file

Check your npm version

If it’s not properly installed, then install it first

run this command npm install typescript -g

It’ll create a corresponding .js file. eg .js

now try node .js

None of above worked for me.

I tried this as well,

was able to compile by hook and crook as follows. Not recommended but just a workaround.

Just install locally using npm , as npm install typescript and verify in node_module folder, if its downloaded. and then run,

Non-admin solution

I do not have admin privileges since this machine was issued by my job.

  • get path of where node modules are being installed and copy to clipboard
    • npm config get prefix | clip
    • don’t have clip? just copy output from npm config get prefix
  • add copied path to environment variables
    • my preferred method (Windows)
    • (Ctrl + R), paste rundll32 sysdm.cpl,EditEnvironmentVariables
    • under User Variables, double-click on Path >New > Paste copied path

None of above answer solve my problem. The fact is that my project did not have type script installed. But locally I had run npm install -g typescript . So I did not notice that typescript node dependency was not in my package json.

When I pushed it to server side, and run npm install , then npx tsc I get a tsc not found. In facts remote server did not have typescript installed. That was hidden because of my local global typescript install.

On Windows 10 i solved it by adding %APPDATA%\npm to the path

I have tried a lot to deploy the Node.js typescript project on Heroku and I have tried different solutions but none of them working for me. So, I have implemented a solution that is to create a build locally which is a dist folder, and just only push dist folder with package.json files, you don’t need to push your src folder to Heroku. and in your script add «start»: «node dist/index.js»

Here are my project structure:

.gitignore file:

just need to add these scripts:

For windows and yarn user, try yarn tsc —init

For mac users, you don’t need to restart your laptop or doing any other commands

Use brew install typescript

Add the path by using command as below in command prompt:
path=%path%;C:\Users\\npm

As in my case, the above path was not registered for command.

%userprofile% in run windows, will give you path to C:\users\

This works perfectly on Mac. Tested on macOS High Sierra

This generates the tsconfig.json file.

I solved this on my machine by just running sudo npm install in the directory that I was getting the error.

Источник

Typescript команда компилятора (tsc), не работающая с tsconfig

Я установил typescript глобально ( npm install typescript -g )

Читайте также:  Не работает парковочный ассистент шкода октавия

Затем создала папку, запустила npm —init , затем npm intall typescript —save-dev — установила typescript @2.1.4

В папке я создаю ‘helloworld.ts`

запустила команду tsc с опцией файла — tsc helloworld.ts и увидела, что она скомпилирована в helloworld.js .

Далее, я хочу использовать tsconfig.json, поэтому я запускаю tsc —init — это не работает, говорит Unknown option ‘init’

Я говорю, хорошо, позвольте мне попробовать добавить tsconfig.json вручную и добавить его в корень папки, как показано ниже:

и я запускаю tsc в командной строке, но он не будет работать и выводит мне синтаксис, пример и параметры того, как использовать tsc Syntax: tsc [options] [file] .

ОТВЕТЫ

Ответ 1

удалить-update-remove-get-rid-off: устаревшие расширения Visual Studio.

или удалите его из пути.

или переименуйте папку, чтобы подтвердить проблему. затем nuke it:)

проверьте, что произойдет, если вы выполните:

также. Мне нужно установить typescript локальный проект, если модуль, от которого вы зависите, зависит от него
вам нужно использовать функцию компилятора в «своем» коде

вам нужно использовать другую версию, чем установленная глобально

для init:

для компиляции

a ‘project’ (на основе tsconfig.json):

где . означает здесь

для компиляции «другого» проекта

Ответ 2

То, что я сделал, чтобы настроить версию Typescript команды tsc в моей системе Windows, было:

Удаление пути Typescript 1.0 здесь. (Запустите button-> Тип: переменные среды, нажмите на опцию (английская версия Windows здесь) и выберите системную переменную среды PATH).

npm link машинопись

И затем я использовал команду refreshenv Chocolatey, чтобы обновить системную переменную среды PATH, которую я настроил.

После запуска команды: tsc -v я получил: Версия 2.2.1

Текущая версия Typescript — 3. 5+, но я глобально установил Typescript 2.2.1, потому что я следую курсу Typescript, используя эту версию.

Источник

TypeScript компилятор или TSC

Что такое TypeScript компилятор, как он работает и как его настроить.

Компилятор TypeScript (также известный как «tsc») является основой многих пакетов, плагинов и инструментов, которые работают с TypeScript. Хотя мы не часто вызываем tsc напрямую, так как настраиваем поведение tsc внутри, используемых нами упаковщиков.

Когда мы устанавливаем TypeScript глобально npm i -g typescript — получаем инструмент под названием tsc . Если запустим эту команду с флагом help tsc —help , то увидим большое количество опций, которые идут с ним. Основные из них, на которые стоит обратить внимание — это первые примеры вверху Examples:

Если создадим файл hello.ts , внутри напишем const four:number = 2 + 2 , а затем запустим tsc hello.ts , то получим скомпилированный файл hello.js со значением var four = 2 + 2; .

Использовать tsc таким образом мы будем редко, потому что tsc включен в плагины такие как Webpack, Parcel и Angular CLI.

Вместо этого мы используем tsc —init . Она создает файл в корне директории с именем tsconfig.json . В нем находятся все значения по умолчанию. Это очень удобно, так как вместо того, чтобы определять все эти параметры в командной строке при его вызове, мы определяем их в этом файле конфигурации TS. Когда запустим команду tsc , то компилятор будет брать настройки с tsconfig.json .

Также, мы можем поменять настройки конфигурации, например, поменять значение ourDir на ./dist . Теперь все скомпилированные файлы должны сохраняться во внешний каталог ./dist .

Всё, что определено в этом файле, будет указывать, какие параметры компилятор TypeScript будет использовать при компиляции. Когда TypeScript начинает “жаловаться” на то, что ты не используешь достаточно типов, можно начать отключать некоторые из этих предупреждений или ошибок.

Источник

Оцените статью