Skip to main content

TypeScript 别名

默认情况下不支持 Typescript 别名,因为我们使用的 ESBuild Webpack 加载器不支持它们。 不过你可以通过修补 Webpack 配置 来使它们解析。

🌐 Typescript aliases are not supported by default, since the ESBuild Webpack loader we have does not support them. You can however patch the Webpack config to make them resolve.

假设你有一个文件:

🌐 Assuming you have a file:

 └── src/
   ├── lib/
   │   ├── one.ts
   │   ├── two.ts
   ├── Root.tsx
   └── index.ts

并且你的 tsconfig.json 包含以下 paths

🌐 and your tsconfig.json has the following paths:

{
  "compilerOptions": {
    "paths": {
      "lib/*": ["./src/lib/*"]
    }
  }
}

你可以将别名添加到 Webpack 中,但你需要手动添加每一个别名:

🌐 you can add the aliases to Webpack, however you need to add each of them manually:

import path from 'path';
import {Config} from '@remotion/cli/config';

Config.overrideWebpackConfig((config) => {
  return {
    ...config,
    resolve: {
      ...config.resolve,
      alias: {
        ...(config.resolve?.alias ?? {}),
        lib: path.join(process.cwd(), 'src', 'lib'),
      },
    },
  };
});

请记住,在 Node.JS API 中,配置文件不起作用,因此你需要将 Webpack 覆盖也添加到 bundle()deploySite() 函数中。

🌐 Remember that in Node.JS APIs, the config file does not apply, so you need to add the Webpack override also to the bundle() and deploySite() functions.

自动同步 Webpack 和 TypeScript 别名

🌐 Automatically syncing Webpack and TypeScript aliases

为了避免在你的 Webpack 覆盖和你的 tsconfig.json 中重复别名,你可以安装 tsconfig-paths-webpack-plugin 并使用它:

🌐 To not duplicate the aliases in your Webpack override and in your tsconfig.json, you can install tsconfig-paths-webpack-plugin and use it:

import {Config} from '@remotion/cli/config';
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';

Config.overrideWebpackConfig((config) => {
  return {
    ...config,
    resolve: {
      ...config.resolve,
      plugins: [...(config.resolve?.plugins ?? []), new TsconfigPathsPlugin()],
    },
  };
});
warning

启用 TypeScript 别名时一个常见的问题是,import {} from "remotion" 会开始映射到你项目中可能存在的 remotion 文件夹,就像我们的一些模板中的情况一样。

我们建议你不要使用 TypeScript 别名。

🌐 We recommend that you don't use TypeScript aliases.

另请参阅

🌐 See also