webpack JS文件无法使用非相对导入来导入类型脚本文件

yeotifhr  于 2022-11-13  发布在  Webpack
关注(0)|答案(1)|浏览(153)

我正在写配置文件(runner.test.js)来运行我的测试用例。我有一个项目,其中有。js,。ts,。tsx,。jsx文件。任何指针都是非常感谢。
问题陈述:相对导入适用于.ts文件,但从js文件导入时,非相对导入不适用。

import { SubApplicationType } from 'midfx/types/types.ts'; ( non-relative imports not work )
import { SubApplicationType } from '../midfx/types/types.ts'; ( relative import is working. Notice  ../ in import statement)

我的所有.ts文件都作为非相对导入导入。我无法将所有导入语句更改为相对导入。
我需要做什么更改,以便在从.js文件导入时,非相对导入适用于.ts文件。
我的项目结构是

src-
    midfx
         types
            types.ts

我正在运行命令[ node runner.test.js ]。我正在设置require('ts-node').register()下的类型脚本的属性

Source Code runner.test.js:
const path = require('path');
const mockCssModules = require('mock-css-modules');

process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';

const mock = require('mock-require');

require('@babel/register');

//TSconfig.js options are made in this method.

require('ts-node').register({
  compilerOptions: {
    allowJs: true,
    baseUrl: "./src",
    paths: { 
      "src/*": ["*"],
      "midfx/*": ["midfx/*"]
    },
  },
  transpileOnly: true,
  files: true,
});

require('jsdom-global')();

const Mocha = require('mocha');
const glob = require('glob');

const mocha = new Mocha({});
const fs = require('fs');

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const appFolder = resolveApp('src');


glob(`${appFolder}/**/*.js`, {}, (err, paths) => {
  paths.forEach(f => {
    const p = f.replace(`${appFolder}/`, '');
    const p1 = p.replace('.js', '');
    mock(p, f);
    mock(p1, f);
  });
});

glob(`${appFolder}/**/*.ts`, {}, (err, paths) => {
    paths.forEach(f => {
    const p = f.replace(`${appFolder}/`, '');
    const p1 = p.replace('.ts', '');
    mock(p, f);
    mock(p1, f);
  });
});

glob(`${appFolder}/**/*.tsx`, {}, (err, paths) => {
  console.log(`tsx folders paths = ${paths.length}`);
  paths.forEach(f => {
    const p = f.replace(`${appFolder}/`, '');
    const p1 = p.replace('.tsx', '');
    mock(p, f);
    mock(p1, f);
  });
});

glob(`${appFolder}/reducers/**/*.spec.js`, {}, (err, allTestFiles) => {
  allTestFiles.forEach((file) => {
    mocha.addFile(file);
  });

  mocha.run(failures => {
    process.on('exit', () => {
      process.exit(failures ? 1 : 0);
    });
  });
});

此致,ilikeflex

xam8gpfp

xam8gpfp1#

您需要在 tsconfig.json 文件中设置baseUrl

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

相关问题