【问题标题】:Typescript is throwing a import statement formatting error where there is none because webpack needs that kind of formatting. How to stop this?Typescript 会抛出一个导入语句格式错误,因为 webpack 需要这种格式。如何阻止这种情况?
【发布时间】:2019-11-02 04:31:36
【问题描述】:

我是 typescript 和 webpack 的新手,我正在尝试建立一个项目来学习如何一起使用它们,但 typescript 显示的错误不是一个。

我的代码的“./testFunction.ts”部分被高亮显示为错误。

import testFunction from "./testFunction.ts";

console.log("imported function: "+testFunction());

错误: 导入路径不能以“.ts”扩展名结尾。考虑导入 './testFunction' 代替.ts(2691)

但我需要 .ts 扩展名,以便 webpack 检测到此导入并将其捆绑。我的 webpack.config.js:

    const path = require('path');

    module.exports = {
        mode: "development",
        entry: './src/index.ts',
        devtool: 'inline-source-map',
        output: {
            path: path.resolve(__dirname, 'build'),
            filename: "bundle.js"
        },
        module: {
            rules: [
                { test: /\.txt$/, use: 'raw-loader' },
                { test: /\.tsx?$/, loader: "ts-loader" }
            ]
        }
    };

{ test: /.tsx?$/, loader: "ts-loader" } 部分告诉 webpack 用 ts-loader 加载什么,如果我省略扩展,webpack 怎么知道要捆绑什么?

当我运行带有 .ts 扩展名的代码时,它可以正常工作,没有它会抛出:

ERROR in ./src/index.ts
Module not found: Error: Can't resolve './testFunction' in '***path***/src'
 @ ./src/index.ts 3:21-46

这不是一个严重的错误,但它很烦人......

【问题讨论】:

    标签: typescript webpack visual-studio-code


    【解决方案1】:

    在不指定扩展名的情况下,Webpack 将查找带有.js 扩展名的文件。

    如果你想让它查找你的 TypeScript 文件,那么你需要告诉 Webpack 也解析 .ts.tsx 扩展:

    const path = require('path');
    
    module.exports = {
      mode: "development",
      entry: './src/index.ts',
      devtool: 'inline-source-map',
      output: {
        path: path.resolve(__dirname, 'build'),
        filename: "bundle.js"
      },
      resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension
        extensions: ['.ts', '.tsx', '.js']
      },
      module: {
        rules: [
          { test: /\.txt$/, use: 'raw-loader' },
          { test: /\.tsx?$/, loader: "ts-loader" }
        ]
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多