簡體   English   中英

無法使用 ts-loader 和 webpack 解析聲明

[英]Can't resolve declaration with ts-loader and webpack

語境

  • "ts-loader": "^6.2.1",
  • “打字稿”:“^3.7.2”,
  • "webpack": "^4.41.2",
  • "webpack-cli": "^3.3.9",
  • "webpack-dev-middleware": "^3.7.2",
  • “webpack-dev-server”:“^3.9.0”

問題

為了導入.html文件,我在html-loader.ts文件中使用以下聲明:

declare module "html-loader!*" {
    const content: string;
    export default content;
}

此聲明在其他文件中使用如下:

import htmlcode from 'html-loader!./template.html';

...

該項目是使用webpackts-loader構建的。

這里是ts-loader使用的tsconfig.json的內容。

{
  "compilerOptions": {
    "outDir": "dist",
    "module": "commonjs",
    "target": "es5",
    "lib": [ "es2015", "dom" ],
    "sourceMap": true,
    "esModuleInterop": true,
    "removeComments": true,
    "noEmitOnError": true,
    "declaration": true
  }
}

這是webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    'lib': './src/index.ts',
  },
  devtool: 'source-map',
  mode: 'development',
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    library: '[name]',
    libraryTarget: 'umd',
    umdNamedDefine: true,
  },
  module: {
      rules: [
        {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/,
          },
      ]
  },
  resolve: {
    extensions: [ '.ts', '.js' ],
  },
};

捆綁包已構建,但構建的命令webpack退出並出現錯誤代碼130和以下消息:

找不到模塊:錯誤:無法解析“/path/to/file_that_use_declaration”中的“html-loader”

任何想法?

使用raw-loader webpack 插件就可以了。

首先,使用npm install raw-loader --save-dev

這是webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    'lib': './src/index.ts',
  },
  devtool: 'source-map',
  mode: 'development',
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    library: '[name]',
    libraryTarget: 'umd',
    umdNamedDefine: true,
  },
  module: {
      rules: [
        {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/,
        },
        {
            test: /\.html$/,
            use: 'raw-loader',
        }
      ]
  },
  resolve: {
    extensions: [ '.ts', '.js' ],
  },
};

這是包含聲明的html-loader.ts

declare module '*.html' {
  const content: any;
  export default content;
}

使用import HTMLVariable from './template.html'; .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM