【问题标题】:Webpack - Getting node modules Into Bundle and loading into html fileWebpack - 将节点模块放入 Bundle 并加载到 html 文件中
【发布时间】:2017-07-08 03:00:16
【问题描述】:

我正在尝试通过 WebPack 在浏览器中使用 node_modules。我已经阅读了教程和开始的步骤,但是卡住了。

我使用 webpack 生成带有下面 webpack 配置的 bundle.js,在 Chrome 浏览器中转到我的 index.html 时出现错误:

Uncaught ReferenceError: require is not defined at Object.<anonymous> (bundle.js:205)

我还需要执行哪些额外步骤才能让浏览器重新识别 require?

index.html

<script src="bundle.js"></script>

<button onclick="EntryPoint.check()">Check</button>

index.js

const SpellChecker = require('spellchecker');

module.exports = {
      check: function() {
            alert(SpellChecker.isMisspelled('keng'));
      }
};

package.json

{
  "name": "browser-spelling",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "node-loader": "^0.6.0",
    "spellchecker": "^3.3.1",
    "webpack": "^2.2.1"
  }
}

webpack.config.js

module.exports = {
    entry: './index.js',
    target: 'node',
    output: {
        path: './',
        filename: 'bundle.js',
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
    module: {
        loaders: [
            {
                test: /\.node$/,
                loader: 'node-loader'
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

【问题讨论】:

    标签: javascript node.js webpack bundle


    【解决方案1】:

    在您的 webpack.config.js 中,您指定要为 Node.js 构建此捆绑包:

    target: 'node',
    

    并且 webpack 决定保留 require 调用,因为 Node.js 支持它们。如果你想在浏览器中运行它,你应该使用target: 'web'

    【讨论】:

    • 一旦我将目标更改为 web,它告诉我:global.process 未定义。有什么想法吗?
    • 看来spellchecker是基于一些系统API,比如Windows 8 Spell Check API(根据github的自述:github.com/atom/node-spellchecker);我认为它不会在浏览器中运行,它仅适用于服务器端。
    • 啊,是的,我用 lodash 替换了拼写检查器,它完美运行!谢谢!
    • @ClickThisNick 所以你删除了拼写检查器并使用了 lodash?
    • @ManojkumarB 我不确定我的评论是什么意思。查看代码似乎我使用了 speller 包,但在 lodash map 函数中使用。老我一定很困惑/耸耸肩
    猜你喜欢
    • 2021-03-21
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2018-01-27
    • 2018-06-04
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多