【发布时间】:2018-11-01 08:26:10
【问题描述】:
我正在尝试使用 typescript 和 webpack 建立一个项目,但是我无法在构建过程中捆绑 html 文件。
我期待index.ts 将所有.html 文件作为字符串导入(它可以很好地导入.ts 文件),这将导致webpack 使用file-loader 捆绑它们并将它们放在dist/examples (因此,如果我有更多 .html 文件,我会将它们导入这里,它们最终也会出现在 dist/examples 中。
我已经尝试过导入的相对名称和绝对名称,但是当我同时使用 webpack 运行以及尝试使用 tsc -p src/tsconfig.json 手动执行时,我得到了错误 TS2307: Cannot find module './file.html'。
我对 typescript 相当陌生,这是我第一次使用 .d.ts 文件,但据我了解,index.d.ts 文件应该告诉 typescript 将所有 .html 文件解析为字符串。
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: {
main: path.resolve(__dirname, 'src', 'main', 'index.ts'),
html: path.resolve(__dirname, 'src', 'res', 'html', 'index.ts')
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
options: {
configFile: 'src/tsconfig.json',
}
},
{
test: /\.html$/,
loader: 'file-loader',
include: path.resolve(__dirname, 'src', 'res', 'html'),
exclude: /node_modules/,
options: {
name: '[name].[ext]',
outputPath: 'examples',
}
}
]
},
resolve: {
extensions: [ '.ts', '.html', '.js' ]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
};
src/tsconfig.json
{
"compilerOptions": {
"outDir": "../dist/",
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"allowJs": false,
"moduleResolution": "node",
"lib": ["es6", "dom"],
"typeRoots": [ "../node_modules/@types", "../types"],
},
"include": [
"main/**/*",
"res/html/**/*"
],
"exclude": []
}
类型/index.d.ts
declare module '*.html' {
const value: string;
export default value
}
src/res/html/index.ts
import test from './test'
import file from './file.html'
src/res/html/file.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>FILE</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>hello world</h1>
</body>
</html>
【问题讨论】:
-
在您的
tsconfig.json中,您确定目录types/可以从"include"获得吗? -
看起来就是这样,我认为声明
typeRoots将包含该类型目录(因为node_modules/@types工作得很好),@Paleo 如果您将其复制为答案,我会标记问题已回答,以便您获得积分 -
好的,完成了..
标签: typescript webpack