首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TS1343:只有当“-模块”选项为“is 2020”、“esnext”或“system”时,才允许使用“import.meta”元属性。

TS1343:只有当“-模块”选项为“is 2020”、“esnext”或“system”时,才允许使用“import.meta”元属性。
EN

Stack Overflow用户
提问于 2021-12-21 19:12:03
回答 4查看 12.2K关注 0票数 21

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

代码语言:javascript
运行
复制
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相关的软件包:

代码语言:javascript
运行
复制
// 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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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' ),
        } ),
    ],
} )

尝试过

  • module在tsconfig.json中设置为es2020esnextsystem

所有这些都没有清除或更改终端错误。

上面是否有错误的配置,妨碍Jest正确运行babel?

EN

回答 4

Stack Overflow用户

发布于 2022-03-02 13:25:54

tsconfig.json中,尝试按如下方式设置compilerOptions

代码语言:javascript
运行
复制
{
  "compilerOptions": {
    "module": "es2022",
    "moduleResolution": "Node"
  },
  ...
}
票数 12
EN

Stack Overflow用户

发布于 2022-03-29 19:24:29

  1. 安装vite-插件-环境插件(https://www.npmjs.com/package/vite-plugin-environment)
  2. 在靠近.env的项目根文件夹中创建package.json文件
  3. .env文件中提供env变量
  4. 将所有import.meta.env.YOUR_VAR更改为process.env.YOUR_VAR
  5. 打开vite.config.ts并列出vite-plugin-环境:
代码语言:javascript
运行
复制
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错误。

这篇文章帮助我在Vite项目中建立了Jest。

票数 6
EN

Stack Overflow用户

发布于 2022-08-22 20:02:45

您可以使用以下命令按照开玩笑的文件运行测试,同时在ts配置文件中将allowSyntheticDefaultImports设置为"true“,这两个更改为我解决了错误。

代码语言:javascript
运行
复制
 yarn NODE_OPTIONS=--experimental-vm-modules npx jest

代码语言:javascript
运行
复制
npm NODE_OPTIONS=--experimental-vm-modules npx jest

确保您安装了相应的模块。这篇文章,有适当的ts,jest和babel配置添加。(我已为遇到此错误的任何人共享我的配置文件。这篇文章非常方便地了解了最初的设置需求。)

代码语言:javascript
运行
复制
//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"
      ],
    }

代码语言:javascript
运行
复制
//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',
                    },
                },

            ]
        ],
    };

};

代码语言:javascript
运行
复制
    //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',
      }
    };

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70440505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档