javascript - `import username from ' ./username.txt '` 与 typescript+webpack 给出 `undefined`

标签 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 ,您可以克隆并运行它

最佳答案

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

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

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

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

关于javascript - `import username from ' ./username.txt '` 与 typescript+webpack 给出 `undefined`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475084/

相关文章:

javascript - jQuery 通过 1 次调用重新加载多个数据表

javascript - jQuery UI : Best way to create two drag/drop lists where one is a Sortable, 其他办法就掉了吗?

javascript - Webpack 在脚本中导入一个节点模块

javascript - React Suspense 在错误的目录中查找 block

javascript - Jquery 自动完成对象传递

javascript - 如何使用nodeJS下载文件

typescript - Angular 2日期反序列化

javascript - 为什么我的嵌套折叠元素没有触发 "show/shown/hide/hidden.bs.collapse"?

debugging - 如何调试 Angular 2 Typescript 应用程序

javascript - Webpack dev server livereload on angular 2 模板文件