rollup [plugin typescript] Note that you need plugins to import files that are not JavaScript等常见的错误。

这里说下我的环境:

...

  "devDependencies": {
    ...,
    "@rollup/plugin-typescript": "^12.1.2",
    "@tsconfig/node22": "^22.0.0",
    "typescript": "^5.8.2"
  },
  "dependencies": {
    "@rollup/plugin-typescript": "^12.1.2",
    "cross-env": "^7.0.3",
    "rollup": "^4.36.0",
    "tslib": "^2.8.1",
    ...,
  }

重要:以下有 ... 三个点的都代表**省略的代码**。

Property 'XXXField' has no initializer and is not definitely assigned in the constructor.

@rollup/plugin-typescript TS2564: Property 'XXXField' has no initializer and is not definitely assigned in the constructor.

出现这个问题是你声明的class字段未进行初始化,让你进行初始化。

问题示例代码:

type int = number;

class Data {
  name: string;
  age: int;
  sex: string;
}

解决方法就是把上面的字段声明到constructor中,就可以解决问题了。

...
constructor(name: string, age: int, sex: String) {
}
...

又或者如果你确定这个数据字段不为空,在使用前会赋值,那么就添加ts特有的明确赋值断言(!)运算符。

...
class Data {
  name!: string;
  age!: int;
  sex!: string;
}

或者第三种方法修改tsconfig.json配置文件,添加strictPropertyInitialization编译选项

更多信息,请前往Typescript classes的文档

Declarations with initializers cannot also have definite assignment assertions.

@rollup/plugin-typescript TS1263: Declarations with initializers cannot also have definite assignment assertions.

出现这个问题说明你在赋值断言和赋值初始化操作了。

...
class Data {
  name!: string;
  age!: int;
  sex!: string = "保密";
}

// 修复后

class Data {
  name!: string;
  age!: int;
  sex: string = "保密";
}

上边的结构就是 断言(!) 和 赋值表达式(=) 一起使用了。
去掉(!)号就可以了。

@rollup/plugin-typescript TS7006: Parameter 'data' implicitly has an 'any' type.

出现这个错误说明你得方法形参或者class字段未声明具体的类型,加上具体的类型即可。

class Data {
  sex;
}

@rollup/plugin-typescript TS2307: Cannot find module 'npm安装的依赖包' or its corresponding type declarations.

出现这个情况,可能你得依赖包缺失,使用如npm install重新安装下即可解决,或者所需的依赖包不在package.json文件中声明。

(!) [plugin typescript] @rollup/plugin-typescript TS5096: Option 'allowImportingTsExtensions' can only be used when either 'noEmit' or 'emitDeclarationOnly' is set.

如果你在使用rollup -c进行构建时,出现了这个错误,那么是@rollup/plugin-typescript依赖包的问题,接下来我们说解决方法。

  1. 首先确认下tsconfig.json文件中已声明以下二个关键的属性
{
  "compilerOptions": {
    ...,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    ...,
  }
}
  1. 确认rollup.config.js文件,plugins数组下typescript插件是否已配置noForceEmit属性。
...
export default {
    input: "src/index.ts",
    output: [
        ...
    ],
    plugins: [
        ...,
        typescript({
            noForceEmit: true,
        }),
        ...,
    ],
};

按照上边的示例代码配置noForceEmit属性为true

noForceEmit: 早期版本的 @rollup/plugin-typescript 要求编译器选项 noEmit 和 emitDeclarationOnly 均为 false,以确保源代码被输入到下一个插件/输出中。现在这两个选项不再为真。该选项将禁止插件强制使用这些选项的值,而是遵从 tsconfig.json 中设置的值。

下面是有关@rollup/plugin-typescript插件,我认为导致这个错误信息的最直接的有关的源代码位置。
下方的代码看下就明白了,因为noForceEmit属性默认为false。

export的是其他文件里的内容,这里为了直观,就放在一个代码块中展示了。

export const FORCED_COMPILER_OPTIONS: Partial<CompilerOptions> = {
  // Always use tslib
  noEmitHelpers: true,
  importHelpers: true,
  // Preventing Typescript from resolving code may break compilation
  noResolve: false
};

export const OVERRIDABLE_EMIT_COMPILER_OPTIONS: Partial<CompilerOptions> = {
  noEmit: false,
  emitDeclarationOnly: false
};

function makeForcedCompilerOptions(noForceEmit: boolean) {
  return { ...FORCED_COMPILER_OPTIONS, ...(noForceEmit ? {} : OVERRIDABLE_EMIT_COMPILER_OPTIONS) };
}

public cannot be used as an identifier in strict mode (Note that you need plugins to import files that are not JavaScript)

错误片段内容:

[!] RollupError: src/service/MyTest.ts (4:8): `public` cannot be used as an identifier in strict mode (Note that you need plugins to import files that are not JavaScript)
src/service/MyTest.ts (4:8)
2: export class SystemInfo33 {
3:     constructor(
4:         public systemName: string, // 这里同时声明了属性并进行了初始化
           ^
5:         public moduleName: string  // 同样适用于 moduleName
6:     ) {}

以上语法是在ts中是合法的,但是在js中是不合法的,上边的问题是在于最终的js解析器在解析ts文件里的内容引起的。
虽然rollup.config.js文件的plugins插件配置了typescript,但是也有可能是tsconfig.json配置不当导致的。
如果你没有配置的话,可参考此处的配置代码:

如果配置内容有错误,欢迎评论区指出,所需的依赖项和插件配置项,按需进行安装,在此就不列出我的package.json文件的依赖内容了。

import typescript from "@rollup/plugin-typescript";
import fs from 'fs';
import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
import replace from '@rollup/plugin-replace';
import terser from '@rollup/plugin-terser';
import json from '@rollup/plugin-json';
import commonjs from '@rollup/plugin-commonjs';
import { babel } from '@rollup/plugin-babel';
import { nodeResolve  } from '@rollup/plugin-node-resolve';

const isProduction = process.env.NODE_ENV === 'production';

// 1. 读取基础配置 `.env`
const baseEnv = dotenv.parse(fs.readFileSync('.env'));

// 2. 根据 NODE_ENV 读取特定环境配置 `.env.production` 或 `.env.development`
const envFile = `.env.${process.env.NODE_ENV || 'development'}`;
if (fs.existsSync(envFile)) {
    const envConfig = dotenv.parse(fs.readFileSync(envFile));
    Object.assign(baseEnv, envConfig); // 用环境配置覆盖基础配置
}

// 3. 处理变量引用,如 `API_URL=${BASE_URL}/api`
dotenvExpand.expand({ parsed: baseEnv });

// 4. 打印最终的环境变量(可选)
console.log('Loaded ENV:', baseEnv);

export default {
    input: "src/index.ts",
    output: [
        {
            file: "dist/my-lib.esm.js",
            format: "es",
        },
        {
            file: "dist/my-lib.cjs.js",
            format: "cjs",
        },
        {
            file: "dist/my-lib.umd.js",
            format: "umd",
            name: "MyLibrary",
        },
        {
            file: "dist/my-lib.iife.js",
            format: "iife",
            name: "MyLibrary",
        },
    ],
    plugins: [
        replace({
            preventAssignment: true, // 避免某些情况报错
            ...Object.fromEntries(
                Object.entries(baseEnv).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)])
            )
        }),
        json(),
        nodeResolve(),
        commonjs(),
        typescript({
            noForceEmit: true,
            tsconfig: './tsconfig.json'
        }),
        babel({ babelHelpers: 'bundled', extensions: ['.js', '.jsx'] }),
        isProduction && terser()
    ],
};

如果上边的typescript插件已安装,也配置完成,还是出现这个错误的话,
那么可能是tsconfig配置导致的。
下面是tsconfig.json文件里的内容(有关node22 tsconfig.json配置内容,点击此处查看):

{
  "compilerOptions": {
    "target": "ES2022",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* 生成 .d.ts 类型文件 */
    "declaration": true,
    "declarationDir": "dist/types",

    /* Bundler mode */
    "moduleResolution": "bundler",
    "isolatedModules": true,
    "moduleDetection": "force",
    "allowImportingTsExtensions": true,
    "noEmit": true,
//    "noEmitOnError": true,

    /* Linting */
    "strict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedSideEffectImports": true,

    "rootDir": "./",
    "esModuleInterop": true,
  },
  "include": [
    "src/**/*",
    "typings/**/*.d.ts"  // 指定自定义类型声明文件的路径
  ],
  "exclude": ["node_modules", "dist"],
  "extends": "@tsconfig/node22/tsconfig.json",
}

解决方法就是把tsconfig.json文件里的allowImportingTsExtensions配置项改为false,
与之关联的noEmitemitDeclarationOnly配置项也要改为false即可(毕竟allowImportingTsExtensions属性需要其他属性搭配使用的)。

当然也可以尝试将其allowImportingTsExtensionsnoEmitemitDeclarationOnly配置项删除掉试试。

其他资源:

TypeScript 5 support: "allowImportingTsExtensions": true causing Cypress configuration error
allowImportingTsExtensions warning
Rollup typescript plugin有关noForceEmit属性的介绍
allowImportingTsExtensions warning
TypeScript 5 support: "allowImportingTsExtensions": true causing Cypress configuration error
Typescript plugin 4.0.0 Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)


以下资源是关联性弱的官网和文档,只为快速抵达。

typescriptlang 官网
Rollup plugin-typescript插件npm仓库地址
tsconfig bases
Rollup 模板rollup-starter-lib
rollupjs configplugin-plugin

posted @ 2025-03-21 15:10  星小梦  阅读(355)  评论(0)    收藏  举报