使用typescript + webpack从'./username.txt'中导入用户名得到`undefined`

时间:2018-09-24 08:11:17

标签: javascript typescript webpack import

我正在演示使用Typescript + Webpack将.txt文件作为字符串导入的演示,几乎完成了,但是有这个问题:

hello.ts

import username from './username.txt'

console.log(`Hello, ${username.trim()}!`)

报告:

TypeError: Cannot read property 'trim' of undefined

我的其他文件:

txt.d.ts

declare module '*.txt' {
    const value: string
    export default value;
}

webpack.config.js

module.exports = {
    mode: 'development',
    entry: './hello.ts',
    devtool: 'inline-source-map',
    output: {
        path: __dirname,
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [{
            test: /\.ts?$/,
            loader: 'ts-loader'
        }, {
            test: /\.txt$/,
            loader: 'raw-loader'
        }]
    }
}

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "types": [
      "node"
    ]
  }
}

package.json

{
  "scripts": {
    "demo": "webpack && node bundle.js"
  },
  "devDependencies": {
    "@types/jquery": "^3.3.9",
    "@types/node": "^10.10.3",
    "raw-loader": "^0.5.1",
    "ts-loader": "^5.1.0",
    "ts-node": "7.0.0",
    "typescript": "^3.0.3",
    "webpack": "^4.18.0",
    "webpack-cli": "^3.1.0"
  }
}

如果我将hello.ts中的导入代码更改为:

import * as username from './username.txt'

console.log(`Hello, ${username.trim()}!`)

它将出现另一个类型错误:

console.log(`Hello, ${username.trim()}!`)
                               ^^^^^^
TS2339: Property 'trim' does not exist on type 'typeof import("*.txt")'

尽管我可以找到一种使其工作的方法:

const username = require('./username.txt')

但是我仍然想知道如何使用import样式对其进行修复。

此演示项目:https://github.com/freewind-demos/typescript-import-txt-file-as-string-issue-demo,您可以克隆并运行它

1 个答案:

答案 0 :(得分:1)

看起来raw-loader正在生成一个模块,该模块的文本字符串作为CommonJS样式的导出分配,而不是默认导出。您应该更新类型声明和代码来使用它:

declare module '*.txt' {
    const value: string
    export = value;
}

import username = require('./username.txt')

或启用esModuleInterop中的tsconfig.json编译器选项,以使默认导出与导出分配可互操作。您可以阅读有关该问题here的更多信息。