GN.*_*GN. 8 yaml typescript webpack
有没有办法通过 Webpack 将 Yaml 导入 Typescript 文件而不会出现错误?
\n// webpack config\n\nconst path = require('path');\n\nmodule.exports = {\n entry: './src/index.ts',\n mode: 'production',\n module: {\n rules: [\n {\n test: /\\.yaml$/,\n use: 'yaml',\n },\n {\n test: /\\.tsx?$/,\n use: 'ts-loader',\n exclude: /node_modules/,\n },\n ],\n },\n resolve: {\n extensions: ['.tsx', '.ts', '.js'],\n },\n output: {\n filename: 'index.js',\n path: path.resolve(__dirname, 'dist'),\n libraryTarget: 'commonjs',\n },\n};\nRun Code Online (Sandbox Code Playgroud)\n// package.json\n"devDependencies": {\n "yaml-ts-loader": "^1.0.0",\n.....\nRun Code Online (Sandbox Code Playgroud)\ntest.ts在文件中
import examples from './test-examples.yaml';\n\ndescribe('', () => {...})\nRun Code Online (Sandbox Code Playgroud)\n结果是
\nTSError: \xe2\xa8\xaf Unable to compile TypeScript:\ntests/mytest.test.ts:1:22 - error TS2307: Cannot find module './test-examples.yaml' or its corresponding type declarations.\n\n1 import examples from './test-examples.yaml';\nRun Code Online (Sandbox Code Playgroud)\n这适用于 Javascript\n但在 Typescript 中失败
\n有没有办法通过 Webpack 将 Yaml 导入 Typescript 文件而不会出现错误?
\n编辑
\n第二次尝试
\nyaml-loaderglobal.d.tsdeclare module '*.yaml' {\n const data: any;\n export default data;\n}\n\nRun Code Online (Sandbox Code Playgroud)\ntsconfig.json{\n "compilerOptions": {\n "outDir": "./dist",\n "target": "es5",\n "lib": ["dom", "dom.iterable", "esnext", "es2015"],\n "sourceMap": true,\n "noEmitOnError": true,\n "allowJs": true,\n "skipLibCheck": true,\n "esModuleInterop": true,\n "allowSyntheticDefaultImports": true,\n "strict": true,\n "forceConsistentCasingInFileNames": false,\n "moduleResolution": "node",\n "resolveJsonModule": true,\n "isolatedModules": true,\n "module": "commonjs",\n "declaration": true,\n "downlevelIteration": true\n },\n "include": ["global.d.ts", "src"],\n "exclude": ["node_modules", "tests"]\n}\n\nRun Code Online (Sandbox Code Playgroud)\n得到相同的结果
\n这是运行测试的代码片段..(在 package.json 中)
\n"scripts": {\n "test": "mocha -r ts-node/register tests/**/*.test.ts",\n ....\n}\nRun Code Online (Sandbox Code Playgroud)\n并且测试像这样导入 yaml ..
\nimport examples from './test-examples.yaml';
但由于我没有使用 webpack 进行测试(我不认为我是)\n这可能是问题所在吗?是否有必要使用 Webpack 编译我的测试(因为测试文件本身正在导入 YAML),然后在编译版本上运行 Mocha 测试?或者说没有必要?
\n=============
\n编辑#2
\n我最终回避了这个问题,并使用了fs一个npm将 YAML 转换为 JSON 的模块。
Ale*_*hin 11
Typescript 不知道您有可以导入yaml文件的 webpack,因此它不会考虑不是模块的文件js或将ts其视为模块的文件。您需要明确告诉打字稿,yaml模块是什么以及它们导出什么。这可以通过创建包含以下内容的文件来完成types.d.ts:
declare module '*.yaml' {
const data: any
export default data
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要通过/// <reference path="/path/to/types.d.ts" />在使用它的文件中添加行或将此文件添加到includetsconfig 中的数组来让 typescript 了解此文件。
yaml-ts-loader顺便说一下,应该.d.ts为每个yaml文件生成文件,所以如果确实如此,您也可以将它们添加到includetsconfig 或/// <reference />它们中
| 归档时间: |
|
| 查看次数: |
10031 次 |
| 最近记录: |