hea*_*LOW 4 javascript typescript webpack webpack-loader .d.ts
作为一个有趣的项目,我正在制作一个用于创建原生 Web 组件的“框架”。我创建了一个 webpack 加载器,它解析自定义.comp文件中的一些 XML并导出一个 es2015 类。不幸的是,我找不到.comp在我的打字稿文件中导入这些文件的方法。
我试过在一个普通的 javascript 文件中导入我的自定义文件,一切都按预期工作;我可以看到我创建的加载器正在运行,并且得到了预期的输出。但是当我尝试导入打字稿文件时,我只是收到错误Cannot find module 'test/test.comp'。我尝试创建一个空的声明文件并注意到错误消息更改为File '[path]/test/test.d.ts' is not a module
这是我的 webpack 配置:
mode: 'development',
watch: true,
entry: './test/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.ts/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.comp/,
use: path.resolve(__dirname, 'core/compose-loader.js'),
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.ts', '.comp'],
alias: {
'core': path.resolve(__dirname, "core/"),
'test': path.resolve(__dirname, "test/")
}
}
Run Code Online (Sandbox Code Playgroud)
还有我的 tsconfig.json
{
"compilerOptions": {
"outDir": "build",
"baseUrl": ".",
"paths": {
"core": ["core/*"],
"test": ["test/*"]
},
"target": "es2015",
"typeRoots": ["./core"]
},
"include": [
"test/*.ts"
],
"exclude": [
"core",
"node_modules",
"**/*.comp"
]
}
Run Code Online (Sandbox Code Playgroud)
sko*_*ovy 12
您可以定义类型所有这些文件*.comp中的一个declarations.d.ts文件(或任何名称你选择)。
declare module "*.comp" {
const value: any; // Add better type definitions here if desired.
export default value;
}
Run Code Online (Sandbox Code Playgroud)
您可能还需要将此添加到typeRoots您的tsconfig.json
{
"compilerOptions": {
// Other configuration...
"typeRoots": [
"./src/declerations.d.ts"
]
}
}
Run Code Online (Sandbox Code Playgroud)
现在,import value from "./test.comp"应该按预期工作(至少是类型)。