Luk*_*ker 3 typescript webpack
我需要使用webpack从打字稿中导入原始数据。这是我的设置:
$ tree
.
+-- file.txt
+-- main.ts
+-- package.json
+-- tsconfig.json
+-- webpack.config.js
Run Code Online (Sandbox Code Playgroud)
file.txt
file-content
Run Code Online (Sandbox Code Playgroud)
main.js
import file from './file.txt';
console.log(file);
Run Code Online (Sandbox Code Playgroud)
package.json
{
"devDependencies": {
"raw-loader": "^0.5.1",
"ts-loader": "^3.1.1",
"typescript": "^2.6.1",
"webpack": "^3.8.1"
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"baseUrl": "app"
},
"exclude": [
"node_modules"
]
}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
当我运行weback时,它说找不到模块:
ERROR in ./main.ts
[tsl] ERROR in /tmp/test/main.ts(1,18)
TS2307: Cannot find module './file.txt'.
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何将txt数据导入打字稿文件?例如,在编写角度组件并导入html模板以将其分配给该组件的template属性时,这很有用。
我global.d.ts在 src 根目录中添加了一个全局定义文件并添加:
declare module "*.txt" {
const content: any;
export default content;
}
Run Code Online (Sandbox Code Playgroud)
我不需要任何额外的tsconfig.json,我只需要标准的 webpack 规则raw-loader:
rules: [
{
test: /\.txt$/i,
loader: 'raw-loader',
},
Run Code Online (Sandbox Code Playgroud)
然后我可以将一个纯文本文件导入./source.js.txt到 ts 变量中,如下所示:
import txt from './source.js.txt'
Run Code Online (Sandbox Code Playgroud)
与 webpack 相比,这似乎更重要的是让 TS 满意。关键似乎是模块定义。如果需要,可以是全局的,也可以是每个文件的。
所以我终于让它工作了。我在.d.ts文件中添加了模块声明:
declare module '*.txt' {
const content: any;
export default content;
}
Run Code Online (Sandbox Code Playgroud)
然后只有我这样导入.txt文件:
const someTextContent = require('./some.txt');
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要使用import关键字,请按以下方式使用它:
import * as someTextContent from './some.txt';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3440 次 |
| 最近记录: |