2017-04-02 451 views
3

我正在尝试构建一个简单文件,该文件依赖于使用UMD导出构建的库。使用webpack导入UMD内置模块导致严重依赖错误

// main.ts 
import { parseTree } from 'jsonc-parser'; 

const tree = parseTree('{ "name: "test" }'); 

console.log(tree); 

它编译罚款,但的WebPack吐出相关性错误:

Hash: 85004e3e1bd3582666f5 Version: webpack 2.3.2 Time: 959ms Asset Size Chunks Chunk Names dist/bundle.js 61.8 kB 0 [emitted] main build/main.d.ts 0 bytes [emitted] [0] ./~/jsonc-parser/lib/main.js 40.1 kB {0} [built] [1] ./~/jsonc-parser/lib 160 bytes {0} [built] [2] ./~/path-browserify/index.js 6.18 kB {0} [built] [3] ./~/process/browser.js 5.3 kB {0} [built] [4] ./src/main.ts 200 bytes {0} [built] [5] ./~/vscode-nls/lib 160 bytes {0} [optional] [built] [6] ./~/vscode-nls/lib/main.js 5.46 kB {0} [built]

WARNING in ./~/jsonc-parser/lib/main.js 3:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

WARNING in ./~/vscode-nls/lib/main.js 118:23-44 Critical dependency: the request of a dependency is an expression

ERROR in ./~/vscode-nls/lib/main.js Module not found: Error: Can't resolve 'fs' in '.../webpack-typescript-umd/node_modules/vscode-nls/lib' @ ./~/vscode-nls/lib/main.js 7:9-22 @ ./~/jsonc-parser/lib/main.js @ ./src/main.ts

// webpack.config.js 
const path = require('path'); 

module.exports = { 
    entry: './src/main.ts', 
    output: { 
     filename: 'dist/bundle.js' 
    }, 
    resolve: { 
     // Add `.ts` and `.tsx` as a resolvable extension. 
     extensions: ['.ts', '.tsx', '.js'] // note if using webpack 1 you'd also need a '' in the array as well 
    }, 
    module: { 
     loaders: [ // loaders will work with webpack 1 or 2; but will be renamed "rules" in future 
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` 
      { 
       test: /\.tsx?$/, 
       loader: 'ts-loader', 
       options: { 
        configFileName: path.resolve(__dirname, 'tsconfig.json') 
       } 
      }, 
     ] 
    } 
} 

我要保持我的js transpiled文件作为commonjs但我希望捆绑jsonc-parser以及无需重新编译它作为commonjs

我创建了a repo on github显示错误的案例。希望这可以帮助你。

您可以简单地npm install && npm run dist重现错误。

+0

你检查了以下线程:https://stackoverflow.com/questions/38392697/webpack-umd-critical-dependency-cannot-be-statically-extracted –

回答

0

我遇到同样的问题,并希望分享两种方法来解决该问题:

在消耗包由一个单一的模块,就像以前jsonc-parser1.0.1 version,你可以添加以下内容您webpack.config.js

module: { 
    rules: [ 
     // your rules come here. 
    ], 
    noParse: /jsonc-parser|other-umd-packages/ 
}, 

在消耗包包含多个文件,可以使用umd-compat-loader作为一种解决方法。在webpack.config.jsumd-compat-loader装载机添加到您的package.json并配置以下rule

module: { 
    rules: [ 
     // other rules come here. 
     { 
      test: /node_modules[\\|/](jsonc-parser|other-umd-packages)/, 
      use: { loader: 'umd-compat-loader' } 
     } 
    ] 
}, 

如何正确使用test一些提示,可以发现here。最后但并非最不重要的一点是,这个功劳归功于OP of the workaround