我需要使用 webpack 从 typescript 导入原始数据。 这是我的设置:
$ tree
.
+-- file.txt
+-- main.ts
+-- package.json
+-- tsconfig.json
+-- webpack.config.js
文件.txt
file-content
main.js
import file from './file.txt';
console.log(file);
package.json
{
"devDependencies": {
"raw-loader": "^0.5.1",
"ts-loader": "^3.1.1",
"typescript": "^2.6.1",
"webpack": "^3.8.1"
}
}
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"baseUrl": "app"
},
"exclude": [
"node_modules"
]
}
webpack.config.js
const path = require('path');
const config = {
entry: './main.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' },
{ test: /\.tsx?$/, loader: 'ts-loader' },
]
}
};
module.exports = config;
当我运行 webpack 时,它说找不到模块:
ERROR in ./main.ts
[tsl] ERROR in /tmp/test/main.ts(1,18)
TS2307: Cannot find module './file.txt'.
我的问题是:如何将 txt 数据导入 typescript 文件?这在编写角度组件时非常有用,例如,导入 html 模板以将其分配给该组件的模板属性。
最佳答案
所以我终于让它工作了。我在 .d.ts 文件中添加了模块声明:
declare module '*.txt' {
const content: any;
export default content;
}
然后我才像这样导入 .txt 文件:
const someTextContent = require('./some.txt');
您可以找到更多关于此的信息 here .
编辑:
如果你想使用 import
关键字,只需按如下方式使用它:
import * as someTextContent from './some.txt';
关于typescript - 使用 `import` 语句使用 webpack 从 typescript 导入原始文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122504/