我需要使用webpack从typescript导入原始数据。这是我的设置:
$ tree
.
+-- file.txt
+-- main.ts
+-- package.json
+-- tsconfig.json
+-- webpack.config.js
字符串
file.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;
型
当我运行weback时,它说找不到模块:
ERROR in ./main.ts
[tsl] ERROR in /tmp/test/main.ts(1,18)
TS2307: Cannot find module './file.txt'.
型
我的问题是:如何将txt数据导入到typescript文件中?这在编写angular组件时很有用,例如,导入html模板以将其分配给该组件的template属性。
3条答案
按热度按时间qybjjes11#
所以我终于让它工作了。我在.d.ts文件中添加了模块声明:
字符串
只有这样我才导入.txt文件:
型
你可以在这里找到更多关于这一点。
编辑:
如果你想使用
import
关键字,只需如下所示:型
jtoj6r0c2#
我在src根目录下添加了一个全局定义文件
global.d.ts
,并添加了:字符串
我不需要任何额外的
tsconfig.json
,我只需要raw-loader
的标准webpack规则:型
然后我可以导入一个名为
./source.js.txt
的纯文本文件到ts变量中,如下所示:型
它似乎更像是让TS快乐而不是webpack。关键似乎是模块定义。如果需要,可以是全局的或每个文件的。
dkqlctbz3#
在webpack v5之前,通常使用
raw-loader
将文件内容作为字符串导入。现在你可以使用
type: 'asset/source'
导入文件的原始文本。字符串
如果使用Typescript,请在项目文件夹中创建声明文件(选择任意名称):
的数据
这样,无论文件扩展名是什么,您都可以将其作为原始文本导入,只需将
?raw
添加到导入地址即可来源:https://webpack.js.org/guides/asset-modules/