Webpack UMD: 无法静态提取关键依赖项

8
我正在尝试使用webpack构建一个umd库;无论我做什么都会得到一个警告:

警告:D:/Code/Node/sample.io/source/index.ts 3:24 严重依赖项:require函数的使用方式不支持静态提取依赖项

当我尝试require('./index.js')生成的index.js时,会出现以下错误:

错误:找不到模块“。”

为了完整起见,这里是所有我的文件:

webpack.config.js:

module.exports = {
  entry: {
    index: __dirname + '/index'
  },
  output: {
    filename: 'index.js',
    library: 'mylib',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  resolve: {
    root: __dirname,
    extensions: ['', '.ts', '.js'],
  },
  module: {
    loaders: [
      { test: /\.ts$/, loaders: ['awesome-typescript-loader'] }
    ]    
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "umd"
  },
  "exclude": [
    "node_modules"
  ]
}

package.json:

{
  "name": "foo",
  "version": "0.1.0",
  "devDependencies": {
    "awesome-typescript-loader": "^2.0.2",
    "typescript": "^2.0.0",
    "webpack": "^2.1.0-beta.17"
  }
}

index.ts:

export function MyFunc(params) {
  console.log("hello world");
}
  • node -v = v6.3.0(Node.js版本号)
  • npm -v = 3.7.5(npm包管理器版本号)

奇怪的是,我的一个朋友说这对他们来说能够正常工作而没有错误。尽管他使用的是node 4.2.6。如果我将模块更改为commonjs,它完全可以正常运行而没有警告或错误。

3个回答

22
我认为您需要在tsconfig中添加"module": "commonjs",这样TypeScript编译将生成能被Webpack理解的模块,但您仍将从Webpack获得umd输出。
希望这能帮到您。

太棒了,我一直以为 TypeScript 需要输出 UMD,谢谢 :D - Meirion Hughes
6
如果这不是你的代码仓库,该怎么办? - amcdnl
如果我需要导入一个 UMD npm 模块怎么办? - Huan
@zixia 请在你的 webpack.config.js 文件的 output 块中添加 libraryTarget: 'umd'。在 webpack 文档 中有描述。 - knee-cola

5
如果您无法将模块从 umd 更改为 commonjs,因为您只是使用它而没有访问源代码,您可以使用umd-compat-loader作为解决方法。将以下 rule 添加到您的 webpack.config.js 中即可:
module: {
    rules: [
        // other rules come here.
        {
            test: /node_modules[\\|/](name-of-the-umd-package)/,
            use: { loader: 'umd-compat-loader' }
        }
    ]
},

我在此帖子中添加了更多细节。


0
如果你无法修复根本原因,只是想要抑制对于这个特定文件的警告,那么请将以下内容添加到你的webpack配置中(确保将其更改为引起警告的文件):
{
  // The rest of your webpack config...
  ignoreWarnings: [
    {
      module: /regex of the file name causing the warning/,
    },
  ]
}

或者,您也可以通过消息来忽略警告。例如,要忽略包含“Critical dependency”的警告,可以这样做:
{
  // The rest of your webpack config...
  ignoreWarnings: [/Critical dependency/],
}

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