GithubHelp home page GithubHelp logo

notlmn / rollup-plugin-transform-tagged-template Goto Github PK

View Code? Open in Web Editor NEW
5.0 3.0 4.0 11 KB

Apply transformations on static contents of tagged template string literals

Home Page: https://npmjs.com/package/rollup-plugin-transform-tagged-template

License: MIT License

JavaScript 100.00%
rollup template-literals template-strings tagged-template-string-literals rollup-plugin

rollup-plugin-transform-tagged-template's Introduction

rollup-plugin-transform-tagged-template

Apply transformations on contents of tagged template string literals, aka. template strings aka. template literals.

npm

Usage

// rollup.config.js
import transformTaggedTemplate from 'rollup-plugin-transform-tagged-template';

export default {
	input: 'test.js',
	plugins: [
		transformTaggedTemplate({
			tagsToProcess: ['css'],
			transformer(data) {
				// Spaces before and after these characters
				data = data.replace(/\s*([{}()>~+=^$:!;])\s*/gm, '$1');

				// Spaces only after these characters
				data = data.replace(/([",\[\]])\s+/gm, '$1');

				// You only need one space consequent in CSS
				data = data.replace(/\s{2,}/gm, ' ');

				return data.trim();
			}
		})
	],
	output: {
		file: 'build.js'
	}
};

API

tagsToProces: string[]

Refers to the tag names that are to be processed. In the example above, css is the tag that is processed.

Example: tagsToProcess: ['handleCSS'] would target the following template literal.

const result = handleCSS`
	:host {
		display: block;
	}
`;

transformer: (string) => string

Does what it says, one-to-one mapping of part of a template string.

This could sometimes be only part of what you are expecting to get as argument. See example below.

Example:

// code.js
const declaration = handleCSS`color: #212121;`;
const result = handleCSS`
	:host {
		display: block;
		${declaration}
	}
`;
// rollup.js
	// ...
	plugins: [
		transformTaggedTemplate({
			tagsToProcess: ['handleCSS'],
			transformer(data) {
                console.log(data);
				return data;
			}
		})
	],
	// ...

// Output
[
	'color: #212121;',
	'\n\t:host {\n\t\tdisplay: block;\n\t\t',
	'\n\t\t}\n',
]

parserOptions: object

Config options to pass to the Babel parser.

Babel Parser options may be needed depending on how your project is structured. See Babel parser options for all available options.

Example:

// rollup.js
	// ...
	plugins: [
		transformTaggedTemplate({
			parserOptions: {
				sourceType: "module", // treat files as ES6 modules
				plugins: [
					"typescript", // parse the file as TypeScript
					[
						"decorators", // use decorators proposal plugin
						{ decoratorsBeforeExport: true }
					]
				]
			}
		})
	],
	// ...

Related

License

MIT © Laxman Damera

rollup-plugin-transform-tagged-template's People

Contributors

notlmn avatar radium-v avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rollup-plugin-transform-tagged-template's Issues

Allow passing options to Babel Parser

Hello! I came across this package and really appreciate the work put into it.

Our source templates are in Typescript files which use decorators, and the Babel Parser throws errors since we can't set config options.

By adding a parserOptions property and passing it to the parser, I can get working results:

const {
	parserOptions = {},
	tagsToProcess = [],
	transformer = code => code
} = options;

const ast = parse(content, parserOptions);

This would allow me to add the required options to my rollup:

...
plugins: [
    transformTaggedTemplate({
        parserOptions: {
            sourceType: "module",
            plugins: [
                "typescript",
                [ "decorators", { decoratorsBeforeExport: true } ]
            ]
        },
        tagsToProcess: ['html'],
        transformer: transformHTMLTaggedTemplate
    }),
...

I'd be happy to submit a pull request both here and for rollup-plugin-minify-tagged-css-template to add this option.

Pass current tag name to transformer function

For scenarios where multiple types of tags are passed with tagsToProcess, it would be great if the transformer function also passed along the tag name. This would allow for transformers to decide which strategy to use based on the tag:

tagsToProcess: [ "handleHTML", "handleCSS" ],
transformer(data, tag) {
    switch(tag) {
        case "handleHTML":
            // process html
            break;
        case "handleCSS":
            // process CSS
        ...

esm imports of babel not working

I could not get this plugin to work in Vite / rollup 3 without making the following changes:

master...thejustinwalsh:rollup-plugin-transform-tagged-template:fix-esm-babel-imports

I can open a PR, but I am unsure if there is a better solution here. The problem seems to stem from the way node.js handles imports of commonjs modules from esm modules and may have been updated in node > 15? I am using node 16 (lts) and the changes within that branch appear to be neccessary.

[!] (plugin transform-tagged-template) SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"'

Hi,

after adding this plugin to my project, I’m getting the following error when I try to build my project:

SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"' (1:0)
    at Parser._raise (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/error.js:60:45)
    at Parser.raiseWithData (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/error.js:55:17)
    at Parser.assertModuleNodeAllowed (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:308:12)
    at Parser.parseStatementContent (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:268:14)
    at Parser.parseStatement (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:157:17)
    at Parser.parseBlockOrModuleBlockBody (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:874:25)
    at Parser.parseBlockBody (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:850:10)
    at Parser.parseTopLevel (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/statement.js:61:10)
    at Parser.parse (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/parser/index.js:59:10)
    at parse (/home/lxg/repos/tui/tech-enablers/demo/mfe/frontend/node_modules/@babel/parser/src/index.js:58:38)

Here’s my rollup.config.js:

import multi from '@rollup/plugin-multi-entry'
import json from '@rollup/plugin-json'
import resolve from '@rollup/plugin-node-resolve'
import transformTaggedTemplate from 'rollup-plugin-transform-tagged-template'

export default {
  input: ['src/**/*.js'],
  output: {
    file: 'dist/main.js',
    format: 'iife'
  },
  plugins: [
      multi(),
      json(),
      resolve(),
      transformTaggedTemplate({
            tagsToProcess: ['whitespace'],
            transformer(data) {
                // Spaces before and after these characters
                data = data.replace(/\s*([{}()>~+=^$:!;])\s*/gm, '$1');

                // Spaces only after these characters
                data = data.replace(/([",\[\]])\s+/gm, '$1');

                // You only need one space consequent in CSS
                data = data.replace(/\s{2,}/gm, ' ');

                return data.trim();
            }
        })
  ]
}

package.json:

{
    "name": "xxx",
    "private": true,
    "version": "0.0.1",
    "type": "module",
    "description": "xxx",
    "author": "xxx",
    "contributors": [
        {
            "name": "xxx",
            "email": "xxx"
        }
    ],
    "scripts": {
        "dev": "npm-run-all --parallel dev:*",
        "dev:js": "npx rollup -c -w",
        "dev:html": "npx browser-sync start --watch --server --port 8081 --files 'dist/*' --index src/index.html",
        "build": "mkdir -p dist && npx rollup -c --environment BUILD:production && npx terser --compress -m --mangle-props regex=/^_/ -o dist/main.js -- dist/main.js"
    },
    "dependencies": {
        "@lxg/l10n": "^1.2.1",
        "@rollup/plugin-json": "^4.1.0",
        "@rollup/plugin-multi-entry": "^4.0.0",
        "@rollup/plugin-node-resolve": "^9.0.0",
        "npm-run-all": "^4.1.5",
        "rollup": "^2.26.5",
        "rollup-plugin-terser": "^7.0.0",
        "rollup-plugin-transform-tagged-template": "0.0.3"
    },
    "devDependencies": {
        "@lxg/l10n-tools": "^1.2.1",
        "browser-sync": "^2.26.13"
    },
    "l10n": {
        "directory": "l10n",
        "instance": "this.l10n",
        "locales": [
            "de-DE",
            "nl-BE"
        ],
        "sources": [
            "src/**/*.js"
        ],
        "targets": {
            "src/translations.json": [
                "src/**/*.js"
            ]
        }
    }
}

Tested with Node 12 and 14, same effect with both.

Without adding the plugin, or when I comment it out, everything runs smoothly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.