I found a convenient way of turning my Chrome extension into modules (a lot easier to maintain etc.). I made it like this https://stackoverflow.com/a/53033388/9182284 (turning background.js into a module and then using dynamic import to get modules).
The simplified version of importing:
(async () => {
const src = chrome.extension.getURL("your/content_main.js");
const contentMain = await import(src);
contentMain.main();
})();
My question is: how could I implement it in Mozilla Firefox? As I am developing for both browsers (first for Chrome and then later copy stuff over to Firefox files and change what's needed). Earlier I just went the easy way and included all the functions in the files they are needed for Firefox version but as I have like 20 files at least then it gets dull do edit all of them etc.
When I try to use dynamic import in Firefox addon then it just doesn't load the script at all (no error log or anything in console) so I don't exactly know the problem (does Firefox just not support it at all?).
If you don't mind using a build tool, I found that parcel works pretty well for this. Use the web extension plugin.
Install via NPM
$ npm install parcel parcel-plugin-web-extension --save-dev
Build from the terminal
$ parcel build --out-dir dist-firefox dist/manifest.json
Related
I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?
It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.
To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.
To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.
An updated answer for 2022
Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension:
Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).
Chrome Extension CLI
Benefits of using them:
New projects are initiated with a default project file structure. Super helpful.
They support modern Javascript (ES6, ES2021), so modules work fine.
They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.
You can use npm as normal to install any packages/dependencies you need.
Then of course, let the official documentation for Chrome Extensions guide you through the rest.
It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?
Yes, It is possible with esm npm packages.
require is commonjs module loader.
Browser doesn't support commonjs modules system
so that this error showed.
Method 1:
Run npm init -y and add "type" :"module" in your package.json.
create path.js file
add this line in path.js
const fullPath = await import.meta.resolve("npm-pkg-name");
const path = fullPath?.match(/(/node_modules.*)/)[0];
console.log(path);
add this line inside package.json
"path": "node --experimental-import-meta-resolve path.js",
Copy console output text. Replace package name with this copied path.
Method 2:
Install other npm package to find and replace
npm packages' virtual path to real path so that chrome browser will find it.
Install Path-fixxer
Add this line in path.js
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
then run command : npm run path.
Now open browser to test it.
I apologize, my lack of knowledge of how to build modern Javascript apps is showing.
We have a Capacitor app that uses plain Javascript, without any build tools. This works fine. We're trying to add Microsoft Code Push support, via https://github.com/mapiacompany/capacitor-codepush, and we're running into a problem with how to integrate it into our app.
For Capacitor and its plugins, we use tags to include the plugin.js files from the various node_modules/.../dist directories.
If we do this with node_modules/capacitor-codepush/dist/plugin.js, we get an error about missing acquisitionSdk. Including node_modules/code-push/script/acquisition-sdk.js doesn't help.
Ok, so maybe there are a bunch of dependencies? We tried using rollup to see if we could get that to work, but cannot. Using this simple input file:
import { codePush } from 'capacitor-codepush';
console.log("hello");
we get [!] Error: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.
Any help would be appreciated.
The only way I was able to get it working was to switch to using webpack. For reasons I don't understand, my initial attempts using rollup did not work. webpack was the key.
You should run the dist version of your app. Meaning, you should use a bundler like webpack. Unbundled (pure) code can't use these features.
I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?
It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.
To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.
To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.
An updated answer for 2022
Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension:
Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).
Chrome Extension CLI
Benefits of using them:
New projects are initiated with a default project file structure. Super helpful.
They support modern Javascript (ES6, ES2021), so modules work fine.
They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.
You can use npm as normal to install any packages/dependencies you need.
Then of course, let the official documentation for Chrome Extensions guide you through the rest.
It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?
Yes, It is possible with esm npm packages.
require is commonjs module loader.
Browser doesn't support commonjs modules system
so that this error showed.
Method 1:
Run npm init -y and add "type" :"module" in your package.json.
create path.js file
add this line in path.js
const fullPath = await import.meta.resolve("npm-pkg-name");
const path = fullPath?.match(/(/node_modules.*)/)[0];
console.log(path);
add this line inside package.json
"path": "node --experimental-import-meta-resolve path.js",
Copy console output text. Replace package name with this copied path.
Method 2:
Install other npm package to find and replace
npm packages' virtual path to real path so that chrome browser will find it.
Install Path-fixxer
Add this line in path.js
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
then run command : npm run path.
Now open browser to test it.
I'm attempting to use PostCSS to fix the problem where 100vh doesn't account for the browser/navigation bar on mobile devices.
https://github.com/Faisal-Manzer/postcss-viewport-height-correction
The problem is, I have no idea how to set it up and the instructions assume I know how. I have very little experience with JavaScript and don't use any frameworks or know how to, I just do everything in VS Code with no plugins.
I installed the PostCSS extension in VS Code but am unsure what to do next.
The installation says:
"And then add this javascript to public/index.html (for React), or add to template.html (for Preact)."
I don't use React (I don't think?), so what do I do instead?
Then it says:
"Check you project for existed PostCSS config: postcss.config.js in the project root, "postcss" section in package.json or postcss in bundle config.
If you already use PostCSS, add the plugin to plugins list:"
Would postcss.config.js be in my root folder? Am I supposed to create this file?
It then says to do this:
module.exports = {
plugins: [
+ require('postcss-viewport-height-correction'),
require('autoprefixer')
]
}
I added that to my .js file (Or does it go in the css file?), and am getting an error "module is not defined."
Could someone walk me through this as if I had no idea what I'm doing and have only been using JavaScript and VS Code for a week? Because that's where I'm at.
I'm on Windows if that makes a difference.
Part of the instructions say to do:
npm install --save postcss-viewport-height-correction
I don't know where to enter this command. I've come across similar instructions several times, and looking up "How to do npm install" doesn't produce any results. I've largely been avoiding using frameworks and extensions and plugins with JavaScript because I can never figure out how to use them, and every guide I can find assumes I already know what it all means.
Might be a long winded answer, but I'll try to respond to everything.
PostCSS is a JS-based tool for transforming styles with JS plugins. Typically, you use it as a plugin into your front-end build tool such as Webpack, Rollup, etc. You can also use it as a CLI app, manually running your build.
I just do everything in VS Code with no plugins.
Which editor you use is irrelevant. How are you building this content? Is it just plain HTML and CSS files?
I installed the PostCSS extension in VS Code
That extension is just for getting your editor on the same page as your PostCSS config. For example, you might write some CSS with your PostCSS config that will look like totally invalid CSS to your editor, and it would throw errors at this. That extension ensures it follows the same altered rules as your CSS now does, since you're using a tool that changes the rules.
Would postcss.config.js be in my root folder? Am I supposed to create this file?
Yes
I added that to my .js file (Or does it go in the css file?), and am getting an error "module is not defined."
JS, but it's throwing errors because you need to install it
Part of the instructions say to do:
npm install --save postcss-viewport-height-correction
I don't know where to enter this command.
From your terminal. NPM (and Yarn, if you run across it) is a CLI tool for installing Node packages, like PostCSS here.
Here are the instructions for installing Node & NPM: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
I'm trying to run node.js backend server. I've received error unexpected reserved word on import in Node.js file.
The lines in file core.module.js is:
'use strict';
import lodashMixins from './lodashMixins.js'
... other imports and configurations ...
I launch simple command: node core.module.js
It's not uncommon error, but usually it happens with other libraries. I haven't seen solution for Node.js. How should I fix this? I'm using Windows Server.
Edit: I've find out that it's ES6, but how could I launch it? It looks like backend for the application, but I have no idea what command should I use to launch it without errors.
import is a part of ECMAScript 2015 (ES6) standard and as Amit above mentioned it is not currently implemented natively in Nodejs.
So you can use transpiler like babel to run your es6 script
npm install babel
An example based on this answer
app.js
import {helloworld,printName} from './es6'
helloworld();
printName("John");
es6.js
module.exports = {
helloworld: function() { console.log('hello world!'); },
printName: function(name) { console.log(name); }
}
And using require hook in start.js
require("babel/register");
var app = require("./app.js");
And start your app as
node start.js
EDIT
The above answer was base on babel v5.8.23. For babel >= v6
Use require hook in start.js as
require('babel-core/register');
require("./app.js");
Also, transformations are not enabled by default. So you will need to install a preset. In this case use es2015
npm install babel-preset-es2015
And use it in a .babelrc file in root folder
{
"presets": ["es2015"]
}
The import keyword is part of the modules feature in ECMAScript 2015, along with export and a few other specifications.
It is currently not implemented natively in NodeJS, even on the lastest version (v0.12.7), nor is it supported in the ES2015 "friendlier" fork iojs.
You will need to use a transpiler to get that to work.
[edit] it's still unsupported in the latest version (v5.8) despite the existence of an --harmony_modules flag, which does nothing. Your best run is to use babel, as explained here and here
I ran into this issue as I manually install any of these tools outside of Visual Studio. But Visual Studio ships with multiple open source command line tools that are used in modern web development workflows. Here’s how you can tell Visual Studio to use the same version that you have manually installed
Go to Tools –> Options –> Projects and Solutions –> External Web Tools
Set the global PATH environment variable before the internal path, you can just use the arrows at the top-right to change the order.
or
First, find the Node.js installation you already have and use at the command line. By default, Node.js 0.12.7 installs to “C:\Program Files\nodejs”. Add this entry at the top to the path to the node.js directory to force Visual Studio to use that version instead
This may not be the official answer, but I stumbled here after searching around for the 'unexpected reserved word'. After poking around, I discovered my problem was that, in fact, I just needed to run an npm install after having updated my branch from origin / rebasing. Hope this helps someone else who is furiously reverting their code trying to figure out what they broke! :)