Я делаю демонстрацию импорта файлов .txt в виде строк с помощью typScript + webpack, почти готово, но у меня есть эта проблема:
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, вы можете клонировать и запустить его