使用Webpack从Typescript导入html [英] Import html from typescript with webpack

查看:340
本文介绍了使用Webpack从Typescript导入html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用webpack将html导入到typescript中的变量中.

这是我的设置:

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);

template.html:

<p>Hello World !</p>

当我尝试使用webpack进行编译时:

$ ./node_modules/.bin/webpack 

[at-loader] Using typescript@2.5.3 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一起使用...

有人可以打电话给我如何使用webpack/typescript将html加载到变量中吗?或至少我的方法有什么问题.

解决方案

一个简单的解决方法是在加载非TypeScript资产时坚持使用CommonJS的"require":

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

如果您希望继续使用import,则可以配置TypeScript编译器以将文件加载为字符串.下面的方法在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线程此处,其中讨论了其他解决方案./p>

I am trying to import html into a variable in typescript using webpack.

Here is my setup:

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);

template.html:

<p>Hello World !</p>

When I try to compile with with webpack:

$ ./node_modules/.bin/webpack 

[at-loader] Using typescript@2.5.3 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'.

I've been on this for half a day so you can be sure template.html is where it is supposed to be.

From what I understand from webpack config is that the html-loader is supposed to process the file first, so it should load the content of the html file into the variable. At least, this used to work with es6...

Can anyone tel me how to load html into a variable with webpack / typescript? Or at least what is wrong with my approach.

解决方案

An easy workaround is to stick with CommonJS "require" when loading non-TypeScript assets:

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

If you'd prefer to keep using import, it's possible to configure the TypeScript compiler to load the file as a string. The method below worked for me under TypeScript 2.4.2.

Add this block to your project's type declarations file (mine is called typings.d.ts):

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

You should now be able to import html files like this:

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

Full disclosure: my project used different loaders from yours (see below).

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

There's a Github thread here where other solutions are discussed.

这篇关于使用Webpack从Typescript导入html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆