Typescript 2.0 and Webpack importing of HTML as string
我正在尝试借助webpack将HTML文件作为字符串导入(当前使用webpack,因为TypeScript 2.0不支持非ES6目标上的异步/等待)。
我的问题是,即使来自github的html-loader版本支持config标志'exportAsEs6Default',我也无法正确设置它。 有什么办法可以全局设置加载程序选项? 因为如果我将html-loader添加到配置文件中的loaders部分中,则会两次调用该加载器,从而导致内容被嵌套。
我有以下定义文件来支持HTML的导入(例如模块文档中的示例)
1 2 3 4 | declare module"html!*" { const content: string; export default content; } |
相应的导入声明:
1 | import templateString from"html!./Hello.html"; |
我使用的软件包的版本:
1 2 3 4 5 6 7 | "babel-core":"^6.17.0", "babel-loader":"^6.2.5", "babel-preset-es2015":"^6.16.0", "html-loader":"git://github.com/webpack/html-loader.git#4633a1c00c86b78d119b7862c71b17dbf68d49de", "ts-loader":"^0.9.5", "typescript":"2.0.3", "webpack":"^1.13.2" |
和webpack配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | "use strict"; module.exports = { entry:"./WebApp/Hello.ts", output: { path:"./wwwroot/compiled", filename:"app.bundle.js" }, resolve: { extensions: ["",".webpack.js",".web.js",".js",".ts"] }, module: { loaders: [ { test: /\\.ts$/, exclude: /node_modules/, loader:"babel-loader!ts-loader" }, { test: /\\.js$/, exclude: /node_modules/, loader:"babel-loader" } ] } }; |
因此,经过一番修补,我找到了一种方法来完成此任务。 由于我不想在每个import语句中添加" exportAsEs6Default"查询参数,因此我从html的显式加载器更改为配置的加载器。
万一有人知道更好的方法,我将保留这个问题,因为目前我不确定我是否会对这种方法感到满意(无需使用加载程序就可以找到打字本机固有的功能),但是也许 它将帮助其他面临相同问题的人。
因此,上例中的import语句更改为
1 | import templateString from"./Hello.html"; |
连同更新的定义文件
1 2 3 4 | declare module"*.html" { const content: string; export default content; } |
并且webpack配置文件更改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | "use strict"; module.exports = { entry:"./WebApp/Hello.ts", output: { path:"./wwwroot/compiled", filename:"app.bundle.js" }, resolve: { extensions: ["",".webpack.js",".web.js",".js",".ts",".html"] }, module: { loaders: [ { test: /\\.ts$/, exclude: /node_modules/, loader:"babel-loader!ts-loader" }, { test: /\\.js$/, exclude: /node_modules/, loader:"babel-loader" }, { test: /\\.html$/, exclude: /node_modules/, loader:"html-loader?exportAsEs6Default" } ] } }; |
更改使用的软件包。