gpt4 book ai didi

typescript - 使用 webpack 导入 UMD 构建模块会导致关键依赖错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:53 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的文件,该文件依赖于使用 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 转译文件保留为 commonjs 但我也想捆绑 jsonc-parser 而无需将其重新编译为 commonjs.

我创建了 a repo on github显示错误的情况。希望这对您有所帮助。

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

最佳答案

我遇到了同样的问题,想分享两种解决问题的方法:

如果消费包由一个模块组成,就像 1.0.1 version 之前一样的 jsonc-parser ,您可以将以下内容添加到您的 webpack.config.js:

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

如果使用的包包含多个文件,可以使用 umd-compat-loader作为解决方法。将 umd-compat-loader 加载器添加到您的 package.json 并在 webpack.config.js< 中配置以下 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。 .

关于typescript - 使用 webpack 导入 UMD 构建模块会导致关键依赖错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com