React项目导入Browserify打包的bundle.js报错,如何正确使用模块?
Hey there! Let's work through your problem step by step—you're not alone in getting tripped up with Browserify and React's ESLint rules.
First: Which File Should You Import?
You should definitely import the bundle.js file, not dh.js. Here's why:
dh.jsuses CommonJSrequire()syntax, which browsers (and React's build tooling like Webpack) don't natively understand without processing.- Browserify's whole job is to bundle that
require()-dependent code into a single file (bundle.js) that browsers can execute directly. Importingdh.jsdirectly would throw a "require is not defined" error, sobundle.jsis the right choice.
Fixing the 'Unexpected use of 'self'' ESLint Error
That error comes from React's default ESLint rule no-restricted-globals, which flags self as a restricted global variable. Browserify uses self internally in its bundled code, so we need to adjust the ESLint config to allow this.
Here are two reliable solutions:
1. Modify Your ESLint Configuration
If you have a custom ESLint config file (like .eslintrc.js or .eslintrc.json), update the no-restricted-globals rule to exclude self:
// .eslintrc.js module.exports = { // ... other existing config rules: { // Remove 'self' from the restricted globals list 'no-restricted-globals': ['error', 'window', 'document'] } };
If you're using Create React App (which hides the default ESLint config), you can add an override in your package.json:
{ "eslintConfig": { "rules": { "no-restricted-globals": ["error", "window", "document"] } } }
2. Disable the Rule Temporarily for the Import
If you don't want to modify your global ESLint config, add a comment above the import line to disable the rule just for that file:
/* eslint-disable no-restricted-globals */ import './bundle.js'; /* eslint-enable no-restricted-globals */
Bonus: Skip Browserify Entirely (Optional)
Since React projects typically use Webpack under the hood (even Create React App uses it), you might not need Browserify at all. Webpack natively supports CommonJS require() syntax, so you can:
- Uninstall Browserify if you want:
npm uninstall browserify - In your React component, directly use:
const crypto = require('diffie-hellman/browser'); // Or use ES6 import syntax if the module supports it: // import crypto from 'diffie-hellman/browser';
Webpack will handle bundling this module into your app automatically, saving you the extra Browserify step.
内容的提问来源于stack exchange,提问作者hussein h

