使用Webpack在浏览器中使用需求模块 [英] Using webpack to use require modules in browser

查看:70
本文介绍了使用Webpack在浏览器中使用需求模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Tried for the past 2 days to use require('modules') in the browser with webpack, when I could do the same thing in browserify in 5 minutes...

这是我的 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"
    }
}

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

However, no matter what I do I get some sort of error. Currently I am getting:

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

,当我运行webpack时,它会引发以下错误: http://pastebin.com/RgFN3uYm

and when I run webpack it throws these errors: http://pastebin.com/RgFN3uYm

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

I followed https://webpack.github.io/docs/tutorials/getting-started/ and http://www.pauleveritt.org/articles/pylyglot/webpack/ yet I still get these errors.

我尝试使用以下代码运行它: webpack ./main.js -o bundle.js 但这仍然行不通.

I've tried to run it with this: webpack ./main.js -o bundle.js Yet it still doesn't work.

如何解决?

推荐答案

您应添加目录以解决例如

You should add directories to resolve e.g.

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

更新:添加json加载器

Update: Add json loader

npm install --save-dev json-loader

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

fs,net,tls也是供node.js使用的库,不适用于浏览器.您应该添加:

also fs, net, tls are libraries for node.js not for in-browser usage. You should add:

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

这篇关于使用Webpack在浏览器中使用需求模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆