简体   繁体   English

javascript文件中如何导入typescript文件

[英]How to import typescript file in javascript file

I am trying to import a typescript file ( src/index.ts ) in a javascript file( tests/steps/utils.js )我正在尝试在 javascript 文件( tests/steps/utils.js )中导入 typescript 文件( src/index.ts index.ts)

But when I use const index_1 = require("../../src/index");但是当我使用const index_1 = require("../../src/index"); in my javascript file, it gives an error: Cannot find module '../../src/index'在我的 javascript 文件中,它给出了一个错误: Cannot find module '../../src/index'

But the file is right there.但是文件就在那里。 Is there any other way to import a typescript file into a javascript file?还有其他方法可以将 typescript 文件导入 javascript 文件吗?

You can't.你不能。 You need to compile the transcript files into js first.您需要先将脚本文件编译成js。

You can't import a ts into js file.您不能将 ts 导入 js 文件。

If you really need the module in.ts file, try to import from dist folder, where the ts compiler output path, or refactor into javascript.如果确实需要模块 in.ts 文件,尝试从 dist 文件夹导入,ts 编译器 output 路径所在的文件夹,或者重构为 javascript。

Looks like you need babel and webpack .看起来你需要babelwebpack These tools allow js and ts to be used together in both development and build.这些工具可以让jsts在开发和构建中一起使用。

.babelrc file (pay attention to @babel/preset-typescript ): .babelrc文件(注意@babel/preset-typescript ):

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-optional-chaining",
    "@babel/plugin-transform-runtime"
  ]
}

and add something like this to webpack.config.js (pay attention to ts in rules/babel-loader ):并将类似的内容添加到webpack.config.js (注意rules/babel-loader中的ts ):

module: {
  rules: [
    {
      test: /\.(js|ts|jsx)$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
      },
    },
  ],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM