有一种方法可以通过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",
.....
intest.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导入打字稿中,而不会出错?
秒尝试
驱逐YAML-TS-LOADER`
addingyaml-loader
global.d.ts
添加类型
declare module '*.yaml' {
const data: any;
export default data;
}
tsconfig.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"]
}
"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
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一样在本机上加载数据文件:/// <reference />