当我使用 webpack 和 ts-loader 构建项目时,Typescript 环境模块未解析

Posted

技术标签:

【中文标题】当我使用 webpack 和 ts-loader 构建项目时,Typescript 环境模块未解析【英文标题】:Typescript ambient modules are not resolved when i build project with webpack and ts-loader 【发布时间】:2020-08-31 10:56:01 【问题描述】:

我有一个 Angular 9 应用程序,我试图导入在加载时不存在的模块,它会在稍后出现。

import('s1').then( m => 

);

这里 s1 是一个不在 Angular 应用程序内部的模块,但它会通过延迟加载等方式从外部资源加载。

为此,我在 src 文件夹中创建了 decl.d.ts 文件,并告诉 typescript 它是友好的模块,不要抛出错误:

declare module "s1";

这是我的 tsconfig.jsontsconfig.app.json

1.


  "compileOnSave": false,
  "compilerOptions": 
    "baseUrl": "./",
    "paths": 
      "@services/*": ["./src/app/services/*", "./src/app/modules/form/services/*"],
      "@typings/*": ["./src/app/typings/*"],
      "@app/*": ["./src/app/*"],
      "@env/*": ["./src/environments/*"]
    ,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  

    “扩展”:“./tsconfig.json”, “编译器选项”: "outDir": "./dist", “类型”:[“节点”] , “排除”: [ “src/test.ts”, “/.spec.ts” ], “包括”: [ "src//.d.ts" ], “角编译器选项”: “启用常春藤”:假

这是我的 webpack.config.dev.js

const AotPlugin = require("@ngtools/webpack").AngularCompilerPlugin;
const htmlWebpackPlugin = require("html-webpack-plugin");
const  resolve  = require('path');
const path = require('path');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = 

  devtool: 'eval-cheap-source-map',
  mode: "development",
  entry: ["./src/polyfills.ts", "./src/main.ts"],
  node: false,

  output: 
    path: resolve('./dist'),
    publicPath: '/',
    filename: '[name].bundle.js',
    chunkFilename: '[id].chunk.js'
  ,

  devServer: 
    https: true,
    host: 'dev.adjarabet.com',
    port: 443,
    historyApiFallback: true,
    disableHostCheck: true,
    watchOptions: 
      ignored: /node_modules/
    ,
    inline: true,
    open: true,
    hot: true,
    //quiet: true
    //stats: 'minimal'
    stats: 
      colors: true,
      chunks: false,
      hash: true,
      version: true,
      timings: true,
      assets: false,
      children: false,
      source: true,
      warnings: true,
      noInfo: true,
      contentBase: './dist',
      hot: true,
      modules: false,
      errors: true,
      reasons: true,
      errorDetails: true,
    ,  
  ,

  resolve: 
    extensions: ['.ts', '.js'],
    plugins: [new TsconfigPathsPlugin(
       
        configFile: path.resolve("./tsconfig.app.json")
      )
    ]
  ,

  performance: 
    hints: false,
  ,

  module: 
    rules: [
      
        test: /\.ts$/,
        use: ['ts-loader', 'angular2-template-loader'],
        exclude: path.resolve(__dirname, "node_modules")
      , 

      
        test: /\.html$/,
        use: 'html-loader'
      , 

      
        test: /\.scss$/,
        use: ['to-string-loader', 'css-loader', 'sass-loader']
      ,  

      
        test: /\.(eot|svg|cur|ico)$/,
        loader: 'file-loader',
        options: 
          name: `[name].[ext]`,
          limit: 10000
        
      ,
    ]
  ,


  plugins: [

    new ModuleFederationPlugin(
      name: 'shell_app',
      library:  type: 'var', name: 'shell_app' ,
      filename: 'remoteEntry.js',
      remotes: 
        s1: 's1'
      ,
      exposes: 
      ,
      shared: []
    ),    
    new HtmlWebpackPlugin(
      template: "./src/index.html"
    ),
    new ProgressPlugin(
      activeModules: false,
    ),
  ]
;

但是当我运行 npm run srv ( "srv": "webpack-dev-server --config webpack.config.dev.js " ) 我得到以下错误:

ERROR in ./src/app/app.component.ts 78:8-20
Module not found: Error: Can't resolve 's1' in '/home/alecoder/Projects/JS/workable_shell/src/app'
resolve 's1' in '/home/alecoder/Projects/JS/workable_shell/src/app'
  Parsed request is a module
  using description file: /home/alecoder/Projects/JS/workable_shell/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      /home/alecoder/Projects/JS/workable_shell/src/app/node_modules doesn't exist or is not a directory
      /home/alecoder/Projects/JS/workable_shell/src/node_modules doesn't exist or is not a directory
      looking for modules in /home/alecoder/Projects/JS/workable_shell/node_modules
        single file module
          using description file: /home/alecoder/Projects/JS/workable_shell/package.json (relative path: ./node_modules/s1)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /home/alecoder/Projects/JS/workable_shell/node_modules/s1 doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /home/alecoder/Projects/JS/workable_shell/node_modules/s1.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /home/alecoder/Projects/JS/workable_shell/node_modules/s1.js doesn't exist
        /home/alecoder/Projects/JS/workable_shell/node_modules/s1 doesn't exist
      /home/alecoder/Projects/JS/node_modules doesn't exist or is not a directory
      /home/alecoder/Projects/node_modules doesn't exist or is not a directory
      /home/alecoder/node_modules doesn't exist or is not a directory
      /home/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
 @ ./src/app/app.module.ts 16:0-47 63:22-34 80:16-28 87:24-36
 @ ./src/main.ts 5:0-45 9:41-50

它似乎无法解决包含 d.ts 文件的问题。我不明白为什么。

【问题讨论】:

【参考方案1】:

您必须配置 webpack 以将您的模块识别为 external 依赖项。

将以下内容添加到您的webpack.config.js

module.exports = 
    ...
    externals: 
        's1': true,
    
;

【讨论】:

以上是关于当我使用 webpack 和 ts-loader 构建项目时,Typescript 环境模块未解析的主要内容,如果未能解决你的问题,请参考以下文章

当我只希望它在一个文件夹/文件中运行时,WebPack ts-loader 编译所有文件

接口更改时 webpack-dev-server 和 ts-loader 不会重新加载

挂在 ts-loader (webpack) 上的“npm run”

如何使用 webpack-chain 将 appendTsSuffixTo 选项添加到 ts-loader?

带有 ts-loader 的 webpack 线程加载器

从 npm 迁移到 Yarn 2 PnP:ts-loader 找不到 webpack