commit b0767cb34b7bf2a4c9d206251c3068bea92cd5e0 Author: Valentin Silytuin Date: Mon Oct 4 22:19:14 2021 +0400 Initial commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d1ddcc7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89aad19 --- /dev/null +++ b/.gitignore @@ -0,0 +1,201 @@ +# Настройки редакторов + +.idea +.vscode + +# https://github.com/github/gitignore/blob/master/Global/Linux.gitignore + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# https://github.com/github/gitignore/blob/master/Global/Windows.gitignore + +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# https://github.com/github/gitignore/blob/master/Global/Archives.gitignore + +# It's better to unpack these files and commit the raw source because +# git has its own built in compression methods. +*.7z +*.jar +*.rar +*.zip +*.gz +*.tgz +*.bzip +*.bz2 +*.xz +*.lzma +*.cab + +# Packing-only formats +*.iso +*.tar + +# Package management formats +*.dmg +*.xpi +*.gem +*.egg +*.deb +*.rpm +*.msi +*.msm +*.msp + +# https://github.com/github/gitignore/blob/master/Global/Backup.gitignore + +*.bak +*.gho +*.ori +*.orig +*.tmp + +# https://github.com/github/gitignore/blob/master/Node.gitignore + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# next.js build output +.next + +# nuxt.js build output +.nuxt + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# Composer +vendor diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..6874d55 --- /dev/null +++ b/.npmignore @@ -0,0 +1,2 @@ +.editorconfig +.prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..228739b --- /dev/null +++ b/.prettierrc @@ -0,0 +1,15 @@ +{ + "printWidth": 120, + "tabWidth": 4, + "useTabs": true, + "semi": true, + "singleQuote": true, + "quoteProps": "as-needed", + "trailingComma": "es5", + "bracketSpacing": false, + "arrowParens": "always", + "proseWrap": "preserve", + "htmlWhitespaceSensitivity": "css", + "vueIndentScriptAndStyle": false, + "endOfLine": "lf" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..d1cf781 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# babel-plugin-nunjucks + +Плагин для [babel-loader](https://github.com/babel/babel-loader), позволяющий использовать шаблонизатор [Nunjucks](https://mozilla.github.io/nunjucks/) внутри JS-файлов. + +## Установка + +```bash +yarn add -D @advdominion/babel-plugin-nunjucks +``` + +## Использование + +Код для преобразования должен находиться в переменных, имена которых указываются в массиве `varNames`, и быть [шаблонным литералом](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/template_strings). Пример: + +```js +const nunjucksTemplate = ` + {% from "./item.njk" import item as item %} + +
+ {% for n in range(0, 10) %} + {{item()}} + {% endfor %} +
+`; +``` + +Пример конфигурации Webpack: + +```js +[ + { + test: /\.js$/, + exclude: [/mocks\.js$/], + use: [ + { + loader: 'babel-loader', + options: { + cacheDirectory: true, + }, + }, + ], + }, + { + test: /mocks\.js$/, + use: [ + { + loader: 'babel-loader', + options: { + compact: false, + plugins: [ + [ + '@advdominion/babel-plugin-nunjucks', + { + templatesFolder: 'src/templates/', + varNames: ['nunjucksTemplate'], + }, + ], + ], + }, + }, + ], + }, +]; +``` + +## Опции + +- `templatesFolder` - обязательный параметр, путь до папки с файлами шаблонов. +- `varNames` - Массив, обязательный параметр. Имена переменных для преобразования кода шаблонизатора. + +**Важно:** Параметр `cacheDirectory` в опциях babel-loader должен быть отключён. diff --git a/index.js b/index.js new file mode 100644 index 0000000..8883b18 --- /dev/null +++ b/index.js @@ -0,0 +1,23 @@ +const nunjucks = require('nunjucks'); + +module.exports = ({types: t}) => { + return { + visitor: { + Identifier(path, state) { + for (let i = 0; i < state.opts.varNames.length; i += 1) { + if ( + path.parentPath.type === 'VariableDeclarator' && + path.isIdentifier({name: state.opts.varNames[i]}) + ) { + const templatesFolder = state.opts.templatesFolder; + const value = path.parentPath.get('init').node.quasis[0].value.raw; + const env = new nunjucks.Environment(new nunjucks.FileSystemLoader(templatesFolder)); + const render = env.renderString(value); + path.parentPath.get('init').node.quasis = [t.templateElement({cooked: render, raw: render})]; + break; + } + } + }, + }, + }; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..65d6793 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "@advdominion/babel-plugin-nunjucks", + "version": "1.10.0", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://bitbucket.org/advdominion/babel-plugin-nunjucks" + }, + "license": "MIT", + "peerDependencies": { + "@babel/core": "7.x" + }, + "dependencies": { + "nunjucks": "^3.2.3" + } +} diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..d9a220d --- /dev/null +++ b/yarn.lock @@ -0,0 +1,27 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +a-sync-waterfall@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz#75b6b6aa72598b497a125e7a2770f14f4c8a1fa7" + integrity sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA== + +asap@^2.0.3: + version "2.0.6" + resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" + integrity sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY= + +commander@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" + integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== + +nunjucks@^3.2.3: + version "3.2.3" + resolved "https://registry.yarnpkg.com/nunjucks/-/nunjucks-3.2.3.tgz#1b33615247290e94e28263b5d855ece765648a31" + integrity sha512-psb6xjLj47+fE76JdZwskvwG4MYsQKXUtMsPh6U0YMvmyjRtKRFcxnlXGWglNybtNTNVmGdp94K62/+NjF5FDQ== + dependencies: + a-sync-waterfall "^1.0.0" + asap "^2.0.3" + commander "^5.1.0"