Webpack和Express - 关键依赖警告

30

我有以下的webpack.config.ts文件:

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

module.exports = {

  entry: [
    './api/bin/www.ts'
  ],
  output: {
    path: path.resolve( __dirname, './dist/api' ),
    filename: 'index.js'
  },
  module: {
    loaders: [
      { test: /\.ts$/, loader: 'awesome-typescript-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: [ '', '.js', '.ts' ]
  },
  target: 'node',
  node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
};

当我运行webpack时,会收到一个有关依赖项的警告:

WARNING in ./~/express/lib/view.js
Critical dependencies:
78:29-56 the request of a dependency is an expression
@ ./~/express/lib/view.js 78:29-56

我使用的这个express服务器不过是一个“Hello World”示例,并且“功能正常”,但我担心这个警告。

我的谷歌搜索没有揭示任何可行的解决方案。我看到过一个特定的问题实例,但解决方案是通过不显示警告来绕过它。


你能否包含你的 view.js 代码? - Lyubomir
3
尝试使用webpack-node-externals插件 https://www.npmjs.com/package/webpack-node-externals - Everettss
@leo,那不是我的存储库中的文件,我认为它只是通过express包含在内,当我执行import * from express时。 - Aleski
我真的很困惑。OP说文件名是“webpack.config.ts”(重点在于*),但我看到的其他所有内容都说这应该是一个.js文件,实际上它的语法似乎更符合JavaScript文件。这只是一个打字错误吗? - Steve Byrne
@Everettss 真遗憾你没有把那个提示作为答案提供...哈哈。 - bvj
4个回答

73

3
这解决了我的错误,但一些方式它仍未生成块文件 - Webpack: output server.0.chunk.js, Webpack: output server.1.chunk.js, Webpack: output server.2.chunk.js, Webpack: output server.3.chunk.js - mohit
我该如何同时使用import和require? - pczern
@mohit,也许你忘记了nodeExternal的圆括号,就像我一样:external: [nodeExternal()]。 - Bogdan

15

如果只需要根据此处提到的视图库而移除express,您还可以从Webpack配置中明确地针对express进行外部设置。

externals: [{'express': { commonjs: 'express'}}]


不错的解决方案。在我的情况下,我还需要在我的webpack.config文件中添加output: {...clientOutput, libraryTarget: 'commonjs'},以避免在我的捆绑包中出现module.exports = undefined的问题(参考https://github.com/webpack/webpack/issues/2030)。 - Liam Kernighan

3

我的警告只有通过以下方式才得到解决:

module.exports =
{
    target: 'node',
    externals: {
        "express": "require('express')"
    }
}

这将需要安装 node_modules。 - Townsheriff
@Townsheriff 这是必备的,可能使用单独的表达方式无法达到效果。 - undefined

1

除了使用nodeExternals排除所有的npm依赖项进行打包,您还可以通过本地引用来仅排除express,方法是替换原有代码:

import express from 'express';
// Or
const express = require('express');

const express = __non_webpack_require__('express');

那将抑制由express引起的警告


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接