Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a bookmarklet using webpack, bookmarklet-loader, style and css-loader

I am trying to create a bookmarklet using bookmarklet-loader and the style-loader and css-loader. But I am having trouble importing css into my bookmarklet.

This is what I have

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
entry: {
    index: './src/index.js',
    bookmarklet: './src/bookmarklets/bookmarklet.js'
},
output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
},
target: 'web',
module: {
    rules: [
    {
        test: /\.css$/,
        use: [
            'style-loader',
            'css-loader'
        ]
    },
    {
        test: /\.js$/,
        use: [
           'bookmarklet-loader'
        ],
        include: path.join(__dirname, './src/bookmarklets')
    }
    ]
},
plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
        title: 'Development'
    })
]

src/bookmarklets/bookmarklet.js:

import './css/style.css';

/* the rest of my bookmarklet code */

src/index.js:

import bookmarklet from './bookmarklets/bookmarklet';

var add = document.createElement("a");
add.href = "javascript:" + bookmarklet;
add.innerHTML = "Click me";

document.body.appendChild(add);

Simply adds the bookmarklet to a link on a blank page, so I can add the link to my browser.

But running webpack produces this error:

SyntaxError: Unexpected token: string (./css/style.css) at [snipped] node_modules/uglify-js/tools/node.js

I tried adding the following to my webpack.config.js:

{
    test: /\.js$/,
    use: [
       'bookmarklet-loader',
       'style-loader',
       'css-loader'
    ],
    include: path.join(__dirname, './src/bookmarklets')
}

This now compiles fine, but the bookmarklet code contains require statements so when I try and run it in the browser I get an

Uncaught ReferenceError: require is not defined

I have found this and this but have been unable to get this to work.

Edit: To explain simply the question and solution. I am trying to build a bookmarklet, but the bookmarklet-loader I am using is used for importing bookmarklets into other pieces of code. And this bookmarklet-loader in particular is not setup to handle css and templates required by the bookmarklet. I have switched to using a simple webpack config that produces a compiled javascript file and then this tool to convert that to a bookmarklet.

This is my package.json in case if its of help to anyone:

<snip>
"scripts": {
        "build": "webpack && bookmarklet dist/index.js dist/bookmarklet.js && cat dist/bookmarklet.js | xclip -selection clipboard",
}

Now npm run build builds the bookmarklet and copies it to my clipboard so I can update the bookmarklet in the browser.

like image 267
arunkumar Avatar asked Oct 15 '17 11:10

arunkumar


People also ask

What is CSS-loader and style-loader?

css-loader is the npm module that would help webpack to collect CSS from all the css files referenced in your application and put it into a string. And then style-loader would take the output string generated by the above css-loader and put it inside the <style> tags in the index.

How do I load a CSS file into webpack?

To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.

How do I bundle CSS with webpack?

By default, Webpack will inline your CSS as Javascript tags that injects the CSS into the page. This sounds strange but it lets you do hot reloading in development. In production you extract them to a file using the ExtractTextPlugin, and require it with a normal link tag.

What is webpack used for?

This is why webpack exists. It's a tool that lets you bundle your JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts and stylesheets.

How to configure CSS-loader and style-loader in Webpack?

You need two loaders to support CSS in your app: css-loader and style-loader. Let’s look at how we can configure css-loader and style-loader in webpack. You set up a loader with the module keyword in your webpack.config.js. The test keyword tells webpack what kind of files should use this loader.

How to configure basic CSS in a Webpack project?

How to configure basic CSS in a webpack project using style-loader and css-loader Let’s start configuring CSS. I assume you already have a webpack project set up. If you don’t, check out createapp.dev to create your own custom webpack boilerplate. Before we configure CSS support in the webpack setup, let’s first add a CSS file and use it.

How does the bookmarklet work?

The bookmarklet is executing like code in the developer tools console, and bypasses the configured Content Security Policy (CSP). The "Hello, World!" link can just as easily send data to another server, including the input of form fields, or cookies.

What do the two loaders in Webpack do?

When you use two loaders in webpack then it takes the output of the first and sends it as input to the second. In our example it takes the CSS file and runs it through css-loader then it takes the output and runs it as input to the style-loader Let’s look at what the loaders do.


Video Answer


1 Answers

I've also found this question interesting so here's an answer that would still let you use webpack for bundling your bookmarklet code.

The idea is to use a <script> tag and serve the content as a chunk through webpack:

function addScript(codeURL) {
    const scriptElement = document.createElement('script');
    scriptElement.setAttribute('src', codeURL);
    scriptElement.setAttribute('crossorigin', "anonymous");
    document.body.appendChild(scriptElement);
}

With some aditional 'magic', your index.js becomes:

const add = document.createElement("a");
add.href = "javascript:(function(){s=document.createElement('script');s.type='text/javascript';s.src='bookmarklet.bundle.js';document.body.appendChild(s);})()";
add.innerHTML = "Click me";

which is the uglified version of the above function that references your 'bookmarklet.bundle.js' chunk. (this way you don't really need the bookmarklet-loader any more)

The bookmarklet.js source (just a sample):

import './css/style.css';

let elements = require('./someOtherSource');

let list = document.createElement('ul');
for (let i = 0; i < elements.length; ++i) {
    let item = document.createElement('li');
    item.appendChild(document.createTextNode(elements[i]));
    list.appendChild(item);
}
document.body.appendChild(list);

where someOtherSource.js could be as simple as:

module.exports = [ 'a', 'b', 'c'];

and finally, your webpack.config.js becomes:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: {
        index: path.resolve(__dirname, 'src/index.js'),
        bookmarklet: path.resolve(__dirname, 'src/bookmarklets/bookmarklet.js'),
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    target: 'web',
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ]
            },
            {
                test: /\.js$/,
                use: [
                    'babel-loader',
                ],
                exclude: /node_modules/,
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Bookmarklet',
            chunks: [ "index" ],
        })
    ]
};

Again, the advantage I see here is that you get to use your webpack bundling, css/less or whatever other loaders for building your bookmarklet. As reference also see first and second.

like image 63
Andrei Roba Avatar answered Sep 28 '22 03:09

Andrei Roba