My ambition is to include a folder, located in node_modules/. Using Node.js I can do:
var example = require('example');
But in my Google Chrome extension it doesn't work, it throws the error:
Require is not defined.
My ambition is to include a folder, located in node_modules/. Using Node.js I can do:
var example = require('example');
But in my Google Chrome extension it doesn't work, it throws the error:
Require is not defined.
Depends if you want to use it in the background page or in the content script, but I assume you are talking about the background page.
In the manifest file :
"background": {
"scripts": [ "scripts/require.js","scripts/main.js"]
}
In main.js:
require.config({
baseUrl: "scripts"
});
require( [ /*...*/ ], function( /*...*/ ) {
/*...*/
});
then in background.html:
<script data-main="scripts/main.js" src="scripts/require.js>
esbuild
If your project requirements permit, consider using a bundler like esbuild
to help avoid compatibility issues by transpiling the syntax into browser-compatible code. The setup is quick and unlike other bundlers such as webpack
, setup of a config file is not required.
esbuild
is a fast and modern bundler with quick set-up. Other bundlers like parcel
could work too (see detailed guide).
Run the following command to install esbuild
as a dependency (see documentation):
npm install --save-exact esbuild
Once installed, you can execute the following command in your root directory (i.e., where package.json
is located) to bundle your client-side code:
esbuild src/content.js --bundle --outfile=dist/bundle.js
Using esbuild
to bundle content.js
will handle all imported modules, including my-script.js
, and include them in the output bundle.js
.
Please note that src
should be replaced with the correct file path for content.js
, which I assume is a single entry point. Depending on your project requirements, esbuild
supports set up of multiple entry points too (see documentation).
Using a bundler like esbuild
will transpile the files as browser-compatible ES syntax by default, meaning it can handle scenarios where there are files with a mix of ES and CommonJS syntax or files with only CommonJS syntax (see documentation).
Browsers can return errors if ES syntax is not a supported version or is not used consistently for imports and exports in scripts. To handle version incompatibility, we can target a specific version of the ES syntax by using the --target
flag in esbuild
(see documentation).
Chrome extensions support ES6 modules in content scripts. You can use the import statement to include modules:
import example from './path-to-node-modules/example';
I didn't find the way to directly run node modules in snippet of Chrome. However, you can run node debug instead.
Then, the chrome will open a debug window, which you can query yourself by using the url of http://localhost:8080/debug?port=5858; And this debug is based on the v8 debug of Chrome itself.