我有一个 node
模块,它使用依赖于 fs
的模块,例如使用 fs.readFileSync
等。我无法手动删除这些模块因为我的根模块的依赖项位于包依赖项的第二级或第三级,其级别为 0。
鉴于此,
我必须在浏览器中运行这些模块,因此我尝试了 browserify
和 webpack
。
我的 webpack
配置如下
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './pgapi',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
noParse: /node_modules\/json-schema\/lib\/validate\.js/,
loaders: [
{ test: /\.json$/, loader: 'json-loader' }
, {
test: /\.js$/,
loader: "transform?brfs"
}
]
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js']
},
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
plugins: [
//new webpack.optimize.UglifyJsPlugin(),
//new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
__DEV__: true
})
]
};
我使用 browserify
作为 brfs
转换的替代方案来尝试处理 fs.readFileSync
等。
构建bundle.js
后,我运行babel
,因为在Safari
中,没有完全符合ES5严格模式
并且它还处理使用此脚本也不支持的箭头运算符
以及let
和const
:
var fs = require('fs')
var args = process.argv.slice(2);
var code=fs.readFileSync(args[0])
var res=require("babel-core").transform(code, {
plugins: [
"transform-es2015-arrow-functions",
"transform-es2015-constants",
"transform-es2015-block-scoping"]
});
console.log(res.code)
所以我很喜欢
$ webpack
或 $ browserify mymodule.js -o dist/bundle.js -t brfs
然后在 dist/bundle.js
$ Node babelify.js dist/bundle.js > out.js
。
然后发生的是 ReferenceError: Can't find variable: fs
(参见 here )
这似乎是因为 brsf 转换确实适用于静态表达式 eval,因此它无法理解 fs.readFileSync(varname) 中的变量。
我正在使用MacGap在 Xcode 中测试 El Capitan
上的 WebView
客户端代码。
如何在构建时摆脱这个问题?
最佳答案
我也遇到了类似的问题。
确定哪个模块正在调用 mime
并找到替代模块。对我来说,这是url-loader
,它依赖于mime
。
我将其替换为 file-loader
,它不依赖于 mime
,因此不是 fs
。确保卸载url-loader
,因为它仍然会抛出错误!
关于javascript - 如何浏览器化 Node `fs.readFileSync` 以使其在 Chrome/Safari/IE 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546141/