【问题标题】:An import path cannot end with '.ts' - NodeJS and Visual Code导入路径不能以“.ts”结尾 - NodeJS 和可视化代码
【发布时间】:2017-03-29 17:09:55
【问题描述】:

我在尝试构建一个简单的 NodeJS 应用程序时遇到了一个错误:

即使 Visual Code 提示错误,我的代码也开始运行了。当我从 import 语句中删除 .ts 扩展名时,我收到一个错误,即找不到文件。

我正在使用 webpack,但这些文件来自服务器。这是我的文件夹结构:

这是我的 webpack 文件:

var webpack = require('webpack');
var helpers = require('./helpers');

//# Webpack Plugins
var CopyWebpackPlugin = (CopyWebpackPlugin = require('copy-webpack-plugin'), CopyWebpackPlugin.default || CopyWebpackPlugin);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
var ExtractTextPlugin = require('extract-text-webpack-plugin');

//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'My Application',
  baseUrl: '/',
  host: process.env.HOST || '0.0.0.0',
  port: process.env.PORT || 8080,
  ENV: ENV,
  HMR: HMR
};

//# Webpack Configuration
module.exports = {
  metadata: METADATA,

  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.ts',
  },

  resolve: {
    extensions: ['', '.ts', '.tsx', '.js', '.scss'],
    root: helpers.root('src'),
    modulesDirectories: [
      'node_modules',
      'server'
    ]
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material'),
          helpers.root('node_modules/@angular')
        ]
      }

    ],

    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.scss|css$/,
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' }),
        exclude: [ helpers.root('node_modules') ]
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, 
        loader: "url-loader?limit=10000&mimetype=application/font-woff" 
      },
      { 
        test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        loader : 'file-loader'
      }
    ]
  },

  plugins: [

    new ForkCheckerPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(true),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),

    new ExtractTextPlugin("[name].css"),

    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    }),

    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      "Tether": 'tether',
      "window.Tether": "tether"
    })

  ],
  
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};

有人可以帮我吗?谢了!

【问题讨论】:

  • 有一个示例 on the typescript website 导入时不带扩展名:import { Hello } from "./components/Hello";。也许这就是未来的方法?这很烦人,因为它在 vs 代码中丢失了智能感知......

标签: node.js express webpack


【解决方案1】:

对我来说,VSCode 使用不同的 Typescript 版本,因为工作空间依赖于不同的版本。需要从工作区中选择一个。
点击状态栏中的版本:

并从工作区中选择版本。

【讨论】:

    【解决方案2】:

    我遇到了这个问题,我花了一个多小时才意识到我所要做的就是从导入中删除 .ts 扩展名。对我来说:

     // index.ts
    import { renderSection, useConfig, writeToFile } from './hooks.ts'
    
    // changed from `./hooks.ts` to `./hooks`
    import { renderSection, useConfig, writeToFile } from './hooks'
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,我的解决方案是重新运行应用程序。就我而言,我刚刚完成了一些文件到 .tsx 的转换,也许它解释了它。

      【讨论】:

      • 它似乎已经为我解决了这个问题
      【解决方案4】:

      这和TypeScript模块解析有关,你可以在tsconfig.json中的compilerOptions字段下配置baseUrl,例如:

      {
        "compilerOptions": {
          "outDir": "build",
          "allowJs": true,
          "target": "es5",
          "jsx": "react",
          "skipLibCheck": true,
          "allowSyntheticDefaultImports": true,
          "baseUrl": "./src/"
        },
        "include": [
          "src/**/*.tsx?"
        ],
        "exclude": [
          "node_modules",
          "**/__snapshots__/*",
          "**/*.snap",
          "**/*.test.jsx?"
        ]
      }
      

      所以,使用这个配置,假设你有一个文件src/app/alarm/index.tsx,你可以在其中从'src/util/Validator.ts`导入Validator,

      import Validator from 'util/Validator'
      

      【讨论】:

        【解决方案5】:

        这是我用的,效果很好。

        完整的 webpack 配置在这里:https://gist.github.com/victorhazbun/8c97dc578ea14776facef09a115ae3ad

        webpack.config.js

        'use strict';
        const webpack = require('webpack');
        
        module.exports = {
          ...
          resolve: {
            extensions: [".ts", ".tsx", ".js"]
          },
          ...
        };
        

        【讨论】:

        • 此链接已损坏。
        • 链接可能已损坏,但 cod 提供的内容仍然有意义。如果您正在运行 webpack,您可以添加如图所示的 resolve 选项,这将解析 ts 扩展。如果您开始了一个新项目,那么可以,也许集成 webpack 并使用此方法。
        【解决方案6】:

        我不确定这个问题的确切解决方案是什么。显然,解决方案是remove the .ts extension — it is a configuration issue if it cannot find the file。对我来说,当我开始使用 ts-loader 时,配置问题就解决了。

        【讨论】:

          猜你喜欢
          • 2021-09-20
          • 2020-01-29
          • 2021-08-27
          • 2021-03-14
          • 2020-05-02
          • 1970-01-01
          • 2021-02-28
          相关资源
          最近更新 更多