IMPORT YAML通过WebPack进入Typescript

问题描述 投票:0回答:2

有一种方法可以通过WebPack将YAML导入打字稿中,而不会出错?

// webpack config const path = require('path'); module.exports = { entry: './src/index.ts', mode: 'production', module: { rules: [ { test: /\.yaml$/, use: 'yaml', }, { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'index.js', path: path.resolve(__dirname, 'dist'), libraryTarget: 'commonjs', }, };
// package.json
"devDependencies": {
    "yaml-ts-loader": "^1.0.0",
.....
in

test.ts

文件

import examples from './test-examples.yaml'; describe('', () => {...})
ressultsin

TSError: ⨯ Unable to compile TypeScript: tests/mytest.test.ts:1:22 - error TS2307: Cannot find module './test-examples.yaml' or its corresponding type declarations. 1 import examples from './test-examples.yaml';
这为JavaScript工作
但是失败的打字稿

有一种方法可以通过WebPack将YAML导入打字稿中,而不会出错?


eDit

秒尝试

驱逐YAML-TS-LOADER`

adding
    yaml-loader
  • 创建一个
    global.d.ts
  • 添加类型
    declare module '*.yaml' { const data: any; export default data; }
tsconfig.json
  • 获取相同的结果
    
    
here是运行测试的代码的片段。(在package.json中)

{ "compilerOptions": { "outDir": "./dist", "target": "es5", "lib": ["dom", "dom.iterable", "esnext", "es2015"], "sourceMap": true, "noEmitOnError": true, "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": false, "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "module": "commonjs", "declaration": true, "downlevelIteration": true }, "include": ["global.d.ts", "src"], "exclude": ["node_modules", "tests"] }


测试像这样导入yaml。

"scripts": { "test": "mocha -r ts-node/register tests/**/*.test.ts", .... }

但由于我没有使用WebPack进行测试(我不认为我是)
这可能是问题吗?是否有必要使用WebPack编译我的测试(因为是导入YAML的测试文件本身),然后在编译版本上运行Mocha测试?还是不是必需的?
==============

Edit#2

i最终将问题引导并与将yaml转换为json的模块使用
import examples from './test-examples.yaml';

typescript不知道您的WebPack可以让您导入

fs

文件,因此它不将不是

npm

yaml
作为模块的文件。您需要明确告诉Typescript,什么是
js
模块以及它们导出的内容。这可以通过使用此内容创建一个

ts
typescript webpack yaml
2个回答
12
投票

yaml

然后,您需要通过在使用该文件的文件中添加
types.d.ts
行或将此文件添加到tsconfig中的
declare module '*.yaml' {
  const data: any
  export default data
}
数组中来让打字稿了解此文件。
/// <reference path="/path/to/types.d.ts" />
为了为每个文件生成
include

文件,因此,如果实际上确实这样做,您也可以将它们添加到tsconfig或thew hew中的
yaml-ts-loader

您应在“*.d.ts”文件中声明模块类型(如果您没有一个人,请将其放在根部):
.d.ts

我设法使它与
一起工作
yaml
但是现在开玩笑在choking着它

include

(可以在运行应用程序中获取的文件路径)的添加),webpack可以加载yaml像yaml一样在本机上加载数据文件:

5
投票
/// <reference />


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.