2017-09-30 96 views
2

我试图导入HTML到使用的WebPack在打字稿的变量。导入HTML用的WebPack

这里是我的设置:

的package.json:

{ 
    "devDependencies": { 
    "awesome-typescript-loader": "^3.2.3", 
    "html-loader": "^0.5.1", 
    "ts-loader": "^2.3.7", 
    "typescript": "^2.5.3", 
    "webpack": "^3.6.0" 
    } 
} 

webpack.config.js:

const path = require('path'); 
const webpack = require('webpack'); 

module.exports = { 
    context: path.join(__dirname), 
    entry: './main', 
    output: { 
    path: path.join(__dirname, 'dist'), 
    filename: 'app.js' 
    }, 
    resolve: { 
    // Add '.ts' and '.tsx' as resolvable extensions. 
    extensions: [".ts", ".js"], 
    modules: [ 
     "node_modules", 
     path.join(__dirname, 'app'), 
    ], 
    }, 
    module: { 
    rules: [ 
     { 
     enforce: 'pre', 
     test: /\.html$/, 
     loader: 'html-loader', 
     }, 
     // Faster alternative to ts-loader 
     { 
     test: /\.tsx?$/, 
     loader: 'awesome-typescript-loader', 
     options: { 
      configFileName: 'tsconfig.json', 
     }, 
     exclude: /(node_modules)/, 
     }, 
    ], 
    }, 
}; 

main.ts:

import template from './template.html'; 
console.log(template); 

模板。 HTML:

<p>Hello World !</p> 

当我试图用的WebPack编译:

$ ./node_modules/.bin/webpack 

[at-loader] Using [email protected] from typescript and "tsconfig.json" from /tmp/test/tsconfig.json. 


[at-loader] Checking started in a separate process... 

[at-loader] Checking finished with 1 errors 
Hash: d06d08edc313f90c0533 
Version: webpack 3.6.0 
Time: 2194ms 
Asset  Size Chunks    Chunk Names 
app.js 2.72 kB  0 [emitted] main 
    [0] ./main.ts 136 bytes {0} [built] 
    [1] ./template.html 40 bytes {0} [built] 

ERROR in [at-loader] ./main.ts:1:22 
    TS2307: Cannot find module './template.html'. 

我一直在这半天,所以你可以肯定template.html是它应该是。

从我从webpack配置中了解到,html-loader应该首先处理文件,所以它应该将html文件的内容加载到变量中。至少,这个使用ES6工作...

任何人都可以电话我如何加载HTML与的WebPack /打字稿变量?或者至少我的方法出了什么问题。

+0

如果你曾经能够解决这个问题? –

+0

请参阅下面的mamacdon的答案。我缺乏的是html扩展的模块定义。 –

回答

1

一个简单的方法就是坚持使用CommonJS的“规定”加载非打字稿资产时:

const template = require('./template.html'); 

如果你喜欢使用import保持,它可以配置打字稿编译器加载文件作为一个字符串。下面的方法在TypeScript 2.4.2下为我工作。

此块添加到项目的类型声明文件(我称之为typings.d.ts):

// typings.d.ts 
declare module '*.html' { 
    const content: string; 
    export default content; 
} 

您现在应该能够导入HTML文件是这样的:

// main.ts 
import template from './template.html'; 
console.log(template); // <p>Hello world !</p> 

全面披露:我项目使用了不同的装载机(见下文)。

// webpack.config.js 
config.module = { 
    rules: [ 
    { 
     test: /\.ts$/, 
     loader: '@ngtools/webpack' 
    }, 
    { 
     test: /\.html$/, 
     use: 'raw-loader' 
    } 
    ] 
} 

有一个Github上线here有其他解决方案进行了讨论。