使用 yarn 安装的依赖项编译 Typescript

Compiling Typescript with dependencies installed with yarn

我在编译引用纱线安装包的打字稿代码时遇到了一些问题。 Tsc 找不到包,因为 yarn 使用即插即用系统。

tsc错误:

src/main.ts:1:36 - error TS2307: Cannot find module 'electron'.

1 import { app, BrowserWindow } from 'electron';
                                     ~~~~~~~~~~

src/main.ts:2:18 - error TS2307: Cannot find module 'node:path'.

2 import path from 'node:path';
                   ~~~~~~~~~~~

src/main.ts:8:42 - error TS2304: Cannot find name '__dirname'.

8     webPreferences: { preload: path.join(__dirname, 'preload.js') },
                                           ~~~~~~~~~

src/main.ts:23:7 - error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`.

23   if (process.platform !== 'darwin') app.quit();
         ~~~~~~~

src/preload.ts:1:21 - error TS2307: Cannot find module 'node:process'.

1 import process from 'node:process';
                      ~~~~~~~~~~~~~~


Found 5 errors.

我对纱线完全陌生,想测试一下。

我的配置中是否遗漏了什么?到处搜索但找不到任何关于使用 Typescript 和 yarn 安装依赖项的文档。或者甚至 typescript 编译器也可以使用 yarn?也许是我遗漏了生成 node_modules 的命令?使用 yarn 的全部意义在于摆脱它。

tsconfig:

{
  "compilerOptions": {
    "lib": ["es2020", "DOM"],
    "module": "es2020",
    "moduleResolution": "Node",
    "target": "es2020",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "sourceMap": false,
    "removeComments": true,
    "preserveConstEnums": true,
    "outDir": "dist",
    "baseUrl": ".",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "include": ["src/**/*"]
}


package.json:

{
  "name": "ElectroMega",
  "packageManager": "yarn@3.0.2",
  "private": true,
  "devDependencies": {
    "typescript": "^4.4.3"
  },
  "dependencies": {
    "@tsconfig/node14": "^1.0.1",
    "@types/node": "^16.9.6",
    "electron": "^14.0.1"
  }
}

我的源文件在根目录的 src 文件夹中。

正如我在原始问题中提到的评论,来自 yarn documentation:

TypeScript uses its own resolver as well. In this case the situation is a bit more complex - the TS team has some concerns about allowing third-party hooks inside the tsc compiler, meaning that we can’t work with it at the moment. That being said, TypeScript isn’t only tsc and as such we’ve been able to add PnP support to the popular ts-loader - meaning that as long as you compile your TypeScript through Webpack, everything works well! Consult the dedicated section about it for more information.

要在使用 Typescript 时启用 yarn 包解析,您必须将 webpack 与 ts-loader 一起使用。我就是这样解决的。

  • 安装必要的依赖项:

npm install webpack webpack-cli pnp-webpack-plugin ts-loader

  • 在项目根目录中创建一个 'webpack.config.js' 文件,内容如下:
const path = require('path');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');

const commonConfig = {
  mode: 'development',
  devtool: 'source-map',
  plugins: [
    new NodePolyfillPlugin(),
  ],
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  node: {
    __dirname: false,
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    plugins: [PnpWebpackPlugin],
  },
  resolveLoader: {
    plugins: [PnpWebpackPlugin.moduleLoader(module)],
  },
};

module.exports = [
  Object.assign(
    {
      target: 'electron-main',
      entry: { main: './src/main.ts' },
    },
    commonConfig
  ),
  Object.assign(
    {
      target: 'electron-renderer',
      entry: { preload: './src/preload.ts' },
    },
    commonConfig
  ),
];
  • 我将 package.json 的脚本更新为 运行 webpack:
{
  "name": "ElectroMega",
  "packageManager": "yarn@3.0.2",
  "private": true,
  "scripts": {
    "build": "webpack",
    "prestart": "yarn run build",
    "start": "electron ./dist/main.js"
  },
  "devDependencies": {
    "html-webpack-plugin": "^5.3.2",
    "node-polyfill-webpack-plugin": "^1.1.4",
    "pnp-webpack-plugin": "^1.7.0",
    "ts-loader": "^9.2.6",
    "typescript": "^4.4.3",
    "webpack": "^5.54.0",
    "webpack-cli": "^4.8.0"
  },
  "dependencies": {
    "@tsconfig/node14": "^1.0.1",
    "@types/node": "^16.9.6",
    "electron": "^14.0.1"
  }
}
  • 然后您应该可以使用以下命令构建您的代码:

yarn build

我的解决方案是遵循 webpack GettingStarted 部分的结果,该部分解释了我遇到的大部分问题,以及使用 webpack 的基础知识。