vuejs / vue-jest

Jest Vue transformer
MIT License
744 stars 157 forks source link

Cannot use import statement outside a module #461

Open yanzhangshuai opened 2 years ago

yanzhangshuai commented 2 years ago

Hello, I have a problem. The problem should come from my configuration. But I need help.

I used ts-jest、babel-jest and @vue/vue3-jest ,But when I run the jest, I got an error

image

configuration

import type { InitialOptionsTsJest } from 'ts-jest';
import { jsWithTsESM as tsjPreset } from 'ts-jest/presets';

const esModules = ['core-js'].join('|');

const config: InitialOptionsTsJest = {
  rootDir: process.cwd(),
  testEnvironment: 'jsdom',
  // roots: ['<rootDir>/test/'],
  // testRegex: '(/tests/.*|\\.(test))\\.(ts|tsx|js)$',
  preset: 'ts-jest/presets/js-with-ts-esm',
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^(\\.{1,2}/.*)\\.js$': '$1'
  },
  transform: {
    ...tsjPreset.transform,
    [`(${esModules}).+\\.js$`]: 'ts-jest',
    '.vue$': '@vue/vue3-jest'
  },

  globals: {
    'ts-jest': {
      useESM: true,
      // babelConfig: './babel.config.js',
      tsconfig: {
        jsx: 'preserve',
        jsxFragmentFactory: 'h',
        esModuleInterop: true,
        target: 'esnext',
        module: 'esnext',
        sourceMap: true,
        allowJs: true
      }
    },
    // 'babel-jest': {
    //   presets: ['@babel/preset-env'],
    //   plugins: ['@babel/plugin-transform-runtime']
    // },
    '@vue/vue3-jest': {
      compilerOptions: {
        propsDestructureTransform: true,
        refTransform: false
      }
    }
  },
  // testPathIgnorePatterns: ['node_modules'],
  transformIgnorePatterns: [`node_modules/(?!${esModules})`],
  moduleFileExtensions: ['vue', 'ts', 'js'],
  // collectCoverageFrom: ['**/*.{tsx,vue,ts}', '!**/node_modules/**'],
  // coverageReporters: ['html-spa'],
  // coverageDirectory: './report/jest'
};

export default config;

Version

nvh95 commented 2 years ago

Please try this workaround:

npm install --save-dev @babel/preset-env

and add babel.config.js to your root of your project:

// babel.config.js
module.exports = {
  presets: ['@babel/preset-env'],
}

Reference: https://github.com/vuejs/vue-jest/issues/367#issuecomment-880300172

richardeschloss commented 1 year ago

Hi, will the team consider upgrading to ESM eventually? Does anyone out there by any chance have an ESM flavor in a fork of this repo?