NodeJS TS 1343:仅当“--module”选项为“es 2020”、“esnext”或“system”时,才允许使用“import.Meta”元属性

gdrx4gfi  于 12个月前  发布在  Node.js
关注(0)|答案(5)|浏览(286)

Jest.js在代码中遇到import.meta时,我得到一个错误:

FAIL  testFile.test.ts
  ● Test suite failed to run

    testFile.ts:40:10 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.

    40          return import.meta?.env as EnvironmentalVariablesType

字符串
我已经安装了以下babel相关的软件包:

// package.json
    "devDependencies": {
        "@babel/core": "^7.16.5",
        "@babel/preset-env": "^7.16.5",
        "@babel/preset-typescript": "^7.16.5",
        "@vitejs/plugin-react-refresh": "1.3.6",
        "babel-jest": "^27.4.5",
        "jest": "27.3.1",
        "jest-environment-jsdom-global": "3.0.0",
        "react": "17.0.1",
        "ts-jest": "27.0.7",
        "typescript": "4.1.3",
        "vite": "2.6.14"
    "dependencies": {
        "babel-plugin-transform-vite-meta-env": "^1.0.3",
        "babel-preset-vite": "^1.0.4",


babel.config.js如下:

module.exports = {
    plugins: [ 'babel-plugin-transform-vite-meta-env' ],
    presets: [
        [
            '@babel/preset-env',
            { targets: { node: 'current' } },
        ],
        [ '@babel/preset-typescript' ],
        [ 'babel-preset-vite' ],
    ],
}


我的vite.config.js

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import replace from '@rollup/plugin-replace'

// https://vitejs.dev/config/
export default defineConfig( {
    base: '/time/',
    server: {
        port: 9000,
    },
    plugins: [
        reactRefresh(),
        replace( {
            'process.env.NODE_ENV': JSON.stringify( 'development' ),
            'process.env.SHOW_DEV_TOOLS': JSON.stringify( 'true' ),
        } ),
    ],
} )

努力

  • 将tslog.json中的module设置为es2020esnextsystem

这些都没有清除或改变终端错误。
上面是否有一些错误的配置阻止Jest正确运行babel?

bwleehnv

bwleehnv1#

tsconfig.json中,尝试将compilerOptions设置为:

{
  "compilerOptions": {
    "module": "es2022",
    "moduleResolution": "Node"
  },
  ...
}

字符串

e5nqia27

e5nqia272#

1.安装vite-plugin-environment插件(https://www.npmjs.com/package/vite-plugin-environment
1.在package.json附近的项目根文件夹中创建.env文件
1.在.env文件中提供环境变量
1.将您所有import.meta.env.YOUR_VAR更改为process.env.YOUR_VAR
1.打开vite.config.ts并列出vite-plugin-environment:

import EnvironmentPlugin from 'vite-plugin-environment';

...

plugins: [
  react(), 
  ...
  EnvironmentPlugin('all')
]

字符串
Jest将理解process.env.YOUR_VAR,因此如果您将所有import.meta.env.YOUR_VAR更改为process.env.YOUR_VAR,您的测试将通过,而不会出现import.meta.env错误
This article helped me for setting up Jest in my Vite project的函数。

slsn1g29

slsn1g293#

我从jest切换到vitest,这样就消除了这个错误。不需要更改测试代码。
以下是我的vitest.config.js

import { defineConfig } from 'vite';

export default defineConfig({
    test: {
        globals: true,
        environment: 'jsdom'
    }
});

字符串

l7wslrjt

l7wslrjt4#

您可以使用以下命令按照jest documentation沿着运行测试,并在ts配置文件中将allowSyntheticDefaultImports设置为“true”,这两个更改为我解决了错误。

yarn NODE_OPTIONS=--experimental-vm-modules npx jest

字符串

npm NODE_OPTIONS=--experimental-vm-modules npx jest


确保你已经按照这个安装了相关的模块。This article,添加了正确的ts,jest和babel配置。(我已经为遇到这个错误的人分享了我的配置文件。This article非常方便了解初始设置要求。)

//tsconfig.json

    {
      "compilerOptions": {
      
        "target": "ES2020", /* Specify ECMAScript target version: '' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "ES2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "allowJs": true, /* Allow javascript files to be compiled. */
        "allowSyntheticDefaultImports": true,
        "strict": true, /* Enable all strict type-checking options. */
 
        /* Module Resolution Options */
        "moduleResolution": "Node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        "baseUrl": "src", /* Base directory to resolve non-absolute module names. */

        "types": [
          "jest"
        ], /* Type declaration files to be included in compilation. */
        "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
      },
      "include": [
        "src/**/*.ts",
        "./src/**/*.js"
      ],
      "exclude": [
        "node_modules"
      ],
    }

//babel.config.js
export default api => {
    const isTest = api.env('test');
    // You can use isTest to determine what presets and plugins to use.

    return {
        presets: [
            [
                '@babel/preset-env',
                '@babel/preset-typescript',
                {
                    'targets': {
                        'node': 'current',
                    },
                },

            ]
        ],
    };

};

//jest.config.js 
    /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */

    export default {
      preset: 'ts-jest',
      testEnvironment: 'node',
      testTimeout: 20000, //to resolve timeout error
      roots: ['src'], 
      modulePaths: ['node_modules', '<rootDir>/src'],
      testPathIgnorePatterns: [
        '<rootDir>/node_modules/', "/__utils"
      ],
      moduleDirectories: [
       "src"
      ],
      transform: {
        "^.+\\.js?$": "babel-jest",
        "^.+\\.ts?$": "ts-jest"
      },
      transformIgnorePatterns: [""], // you can add any module that you do not want to transform, The first pattern will match (and therefore not transform) files inside /node_modules. 
      testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(js?|tsx?)$",
      "transform": {
        "^.+\\.(t|j)s$": "ts-jest"
      },
      testEnvironment: "node",
      "moduleNameMapper": {
        "src/(.*)": "<rootDir>/src/$1"
      },
      globals: {
        "ts-jest": {
          "useESM": true
        }
      },
      extensionsToTreatAsEsm: ['.ts'],
      moduleNameMapper: {
        '^(\\.{1,2}/.*)\\.js$': '$1',
      }
    };

xienkqul

xienkqul5#

这个问题是从.env变量全局导入的。我有同样的问题,我从以下位置解决:

export const BASE_URL = import.meta.env.VITE_BASE;
const API = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

字符串
收件人:

const BASE_URL = 'http://localhost:5170' // your api backend
const API = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

相关问题