gpt4 book ai didi

node.js - 找不到模块 : Error: Can't resolve 'fs' with webpack

转载 作者:搜寻专家 更新时间:2023-10-31 23:45:20 25 4
gpt4 key购买 nike

我制作了一个由 webpack 构建的小代码。源入口文件是这样的:

import archiver from 'archiver'
import request from 'request'
import mkdirp from 'mkdirp'
import Zip from 'node-zip'
import Zlib from 'zlib'
import path from 'path'
import fs from 'fs'

export default class myTestClass {


constructor (config) {

super (config)

}

//......
}

webpack 配置是:

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


module.exports = {
entry: [
path.resolve("./js/app.js")
],
output: {
path: path.resolve('./build'),
filename: "build.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' },

{ test: /\.scss$/, loader: 'style!css!sass?sourceMap'},
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}

]

},

resolve: {
modules: [
"./js",
"./node_modules"
],
extensions : ['.js', '.jsx', '.json']
},
resolveLoader: {
modules: ['node_modules']
},
node: {
console: true
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
Promise: 'bluebird',
jQuery: 'jquery',
$: 'jquery'
})
]
};

主要的 app.js 只是调用 myTestClass:

import MyClass from './myTestClass.js'

module.exports = async function() {

const myCls = new MyClass();

return '';
};

运行 webpack,我遇到了很多相同的错误:

Module not found: Error: Can't resolve 'fs'

如果我关注 https://github.com/webpack-contrib/css-loader/issues/447 中的评论,即

node:{
fs:'empty'
}

它可以构建,但是在客户端运行代码时,build.js 会弹出一个错误。错误是:fs 未定义。我认为这是因为 Node 的 fs 设置为空。

var fs$ReadStream = fs.ReadStream
ReadStream.prototype = Object.create(fs$ReadStream.prototype)
ReadStream.prototype.open = ReadStream$open

您能否说明如何解决此问题?设置 fs = empty 的用法正确吗?如果正确,build.js 有什么问题?

最佳答案

您可以在客户端使用 webpack.config.js 中的以下代码要求 fs

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 中添加

  externals: nodeModules,
target: 'node',

这将帮助您在客户端要求 fs。

关于node.js - 找不到模块 : Error: Can't resolve 'fs' with webpack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020061/

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