gpt4 book ai didi

javascript - 使用 webpack 在浏览器中使用 require 模块

转载 作者:数据小太阳 更新时间:2023-10-29 05:32:21 24 4
gpt4 key购买 nike

过去 2 天尝试在带有 webpack 的浏览器中使用 require('modules'),当时我可以在 5 分钟内在 browserify 中做同样的事情......

这是我的 webpack.config.js

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

var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});

module.exports = {
entry: "./main.js",
output: {
filename: "bundle.js"
}
}

但是,无论我做什么,我都会遇到某种错误。目前我得到:

bundle.js:390 Uncaught Error: Cannot find module "net"

当我运行 webpack 时它会抛出这些错误:http://pastebin.com/RgFN3uYm

我关注了https://webpack.github.io/docs/tutorials/getting-started/http://www.pauleveritt.org/articles/pylyglot/webpack/但我仍然遇到这些错误。

我试过用这个运行它:webpack ./main.js -o bundle.js 但它仍然不起作用。

如何解决?

最佳答案

您应该添加目录来解析例如

 resolve: {
modulesDirectories: ['./app/', './node_modules']
}

更新:添加 json 加载器

npm install --save-dev json-loader

module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' }
]
}

另外,fs、net、tls 是 node.js 的库,不适合在浏览器中使用。你应该添加:

node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}

关于javascript - 使用 webpack 在浏览器中使用 require 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207277/

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