Popular New Releases in Transpiler
babel-sublime
v11.1.0-rc.1
c2rust
Maintenance Release
core
MetaCall v0.5.7 [2021-10-25]
ruby-next
0.15.0
wax
Binaries for Windows, macOS and Linux
Popular Libraries in Transpiler
by babel javascript
3247 MIT
Syntax definitions for ES6 JavaScript with React JSX extensions.
by immunant rust
2304 NOASSERTION
Migrate C code to Rust
by bridgedotnet csharp
2236 Apache-2.0
:spades: C# to JavaScript compiler. Write modern mobile and web apps in C#. Run anywhere with Bridge.NET.
by wrobstory python
2048 MIT
A Python to Vega translator
by owenthereal go
1459 MIT
Godzilla is a ES2015 to Go source code transpiler and runtime
by polarphp c++
1051 NOASSERTION
The compiler and runtime of PHP programming language
by andrei-markeev c
1045 ISC
Convert Javascript/TypeScript to C
by metacall c
915 Apache-2.0
MetaCall: The ultimate polyglot programming experience.
by beeware python
855 NOASSERTION
A transpiler that converts Python code into Java bytecode
Trending New libraries in Transpiler
by LingDong- c
411 MIT
A tiny programming language that transpiles to C, C++, Java, TypeScript, Python, C#, Swift, Lua and WebAssembly 🚀
by phabelio php
199 MIT
PHP transpiler - Write and deploy modern PHP 8 code, today.
by adsharma python
178 MIT
Python to CLike languages transpiler
by gotranspile go
118 MIT
Another tool for transpiling C to Go.
by abaplint typescript
43 MIT
ABAP to JS transpiler
by mugi-uno ruby
19
A RubyGem that converts Ruby RBS to TypeScript definitions.
by donmccurdy javascript
17 MIT
MikkTSpace vertex tangent calculation for JavaScript/TypeScript/Node.js, using Web Assembly.
by VKCOM typescript
17 MIT
Typescript to PHP translation tool
by bianjieai go
17 Apache-2.0
Golang Implementation of Terse IBC
Top Authors in Transpiler
1
3 Libraries
13
2
2 Libraries
94
3
2 Libraries
28
4
2 Libraries
415
5
2 Libraries
13
6
2 Libraries
58
7
2 Libraries
149
8
2 Libraries
6
9
2 Libraries
14
10
2 Libraries
15
1
3 Libraries
13
2
2 Libraries
94
3
2 Libraries
28
4
2 Libraries
415
5
2 Libraries
13
6
2 Libraries
58
7
2 Libraries
149
8
2 Libraries
6
9
2 Libraries
14
10
2 Libraries
15
Trending Kits in Transpiler
No Trending Kits are available at this moment for Transpiler
Trending Discussions on Transpiler
How to use Local modules in remix-run application in yarn workspaces
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in the package.json of a module in node_modules
Babel and Node - No stack trace on syntax errors
Automatic detection of object property type based on another property value
What are all the ways you can encounter an EmptyStatement in a JavaScript AST?
Regular expression to determine key
Vue project with or without Babel?
What is the javascript find() function as opposed to the Array.find() method?
Do functional language compilers optimize a "filter, then map" operation on lists into a single pass?
Best Practice: Enable React Component in User Input
QUESTION
How to use Local modules in remix-run application in yarn workspaces
Asked 2022-Feb-03 at 13:12i have a yarn
workspace
monorepo
where different packages contain reusable code. like
@pkg/styles
,
@pkg/ui-components
all of these packages are es modules
(import export statements)
and are used in my non ssr application built by webpack like this.
for example
1import { box } from '@pkg/styles'
2import {Button} from '@pkg/ui-components'
3
now i need to add remix-run
to the same monorepo and things work fine until i start importing these local packages. i get this error
1import { box } from '@pkg/styles'
2import {Button} from '@pkg/ui-components'
3import box from './box';
4^^^^^^
5
6SyntaxError: Cannot use import statement outside a module
7 at Object.compileFunction (node:vm:352:18)
8 at wrapSafe (node:internal/modules/cjs/loader:1031:15)
9 at Module._compile (node:internal/modules/cjs/loader:1065:27)
10 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
11 at Module.load (node:internal/modules/cjs/loader:981:32)
12 at Function.Module._load (node:internal/modules/cjs/loader:822:12)
13
if i am not wrong this is happening because esbuild
expects all node_modules
to be pre compiled. and simply ignores them in the transpile phase.
and i need to tell my transpiler to consider my local packages in the transpilation which is super easy to do when we are using webpack
. but i am not sure how to do it in remix-run
and esbuild that it uses internally. there are few issues on remix-run github but nothing seem to be helpful.
ANSWER
Answered 2022-Feb-03 at 13:12as of 3-feb-2022 there is no official support from remix-run for building your local packages inside a yarn workspaces monorepo. i was able to patch up esbuild config and allow local modules to be build. here is the official issue raised on remix run repo.
what i ended up doing is to patch up the remix esbuild configuration
Create esbuild-overrides.js
in the root of the project
add following code
1import { box } from '@pkg/styles'
2import {Button} from '@pkg/ui-components'
3import box from './box';
4^^^^^^
5
6SyntaxError: Cannot use import statement outside a module
7 at Object.compileFunction (node:vm:352:18)
8 at wrapSafe (node:internal/modules/cjs/loader:1031:15)
9 at Module._compile (node:internal/modules/cjs/loader:1065:27)
10 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
11 at Module.load (node:internal/modules/cjs/loader:981:32)
12 at Function.Module._load (node:internal/modules/cjs/loader:822:12)
13const esbuild = require('esbuild');
14const Module = require('module');
15
16function manualExternalsPlugin() {
17 return {
18 name: 'manual-externals-overide',
19 setup(build) {
20 build.onResolve(
21 {
22 filter: /@YourNamespaceOrPackageName/,
23 },
24 (args) => {
25 return {
26 external: false,
27 namespace: args.path,
28 };
29 },
30 );
31 },
32 };
33}
34
35const originalRequire = Module.prototype.require;
36const originalBuild = esbuild.build;
37
38function build(options) {
39 if (options.platform === 'node') {
40 const { plugins } = options;
41 const externalPlugin = plugins.find(
42 (plugin) => plugin.name === 'manual-externals',
43 );
44 const localPlugins = plugins.filter(
45 (plugin) => plugin.name !== 'manual-externals',
46 );
47 localPlugins.push(manualExternalsPlugin());
48 localPlugins.push(externalPlugin);
49 return originalBuild({
50 ...options,
51 plugins: localPlugins,
52 });
53 }
54 return originalBuild({
55 ...options,
56 });
57}
58
59Module.prototype.require = function (id) {
60 // when remix requires esbuild, it will get our modified build function from above
61 if (id === 'esbuild') {
62 return { ...esbuild, build };
63 }
64 return originalRequire.apply(this, arguments);
65};
66
67
update build scripts
1import { box } from '@pkg/styles'
2import {Button} from '@pkg/ui-components'
3import box from './box';
4^^^^^^
5
6SyntaxError: Cannot use import statement outside a module
7 at Object.compileFunction (node:vm:352:18)
8 at wrapSafe (node:internal/modules/cjs/loader:1031:15)
9 at Module._compile (node:internal/modules/cjs/loader:1065:27)
10 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
11 at Module.load (node:internal/modules/cjs/loader:981:32)
12 at Function.Module._load (node:internal/modules/cjs/loader:822:12)
13const esbuild = require('esbuild');
14const Module = require('module');
15
16function manualExternalsPlugin() {
17 return {
18 name: 'manual-externals-overide',
19 setup(build) {
20 build.onResolve(
21 {
22 filter: /@YourNamespaceOrPackageName/,
23 },
24 (args) => {
25 return {
26 external: false,
27 namespace: args.path,
28 };
29 },
30 );
31 },
32 };
33}
34
35const originalRequire = Module.prototype.require;
36const originalBuild = esbuild.build;
37
38function build(options) {
39 if (options.platform === 'node') {
40 const { plugins } = options;
41 const externalPlugin = plugins.find(
42 (plugin) => plugin.name === 'manual-externals',
43 );
44 const localPlugins = plugins.filter(
45 (plugin) => plugin.name !== 'manual-externals',
46 );
47 localPlugins.push(manualExternalsPlugin());
48 localPlugins.push(externalPlugin);
49 return originalBuild({
50 ...options,
51 plugins: localPlugins,
52 });
53 }
54 return originalBuild({
55 ...options,
56 });
57}
58
59Module.prototype.require = function (id) {
60 // when remix requires esbuild, it will get our modified build function from above
61 if (id === 'esbuild') {
62 return { ...esbuild, build };
63 }
64 return originalRequire.apply(this, arguments);
65};
66
67
68"scrips": {
69 "dev:patched": "NODE_OPTIONS='-r ./esbuild-overrides' remix dev",
70 "build:patched": "NODE_OPTIONS='-r ./esbuild-overrides' remix build"
71}
72
QUESTION
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in the package.json of a module in node_modules
Asked 2022-Jan-31 at 17:22This is a React web app. When I run
1npm start
2
This error occurred
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24
This error only occurs when I run this on this specific computer, which I do not have superuser access to. It works on other computers.
For reference, this is ./node_modules/postcss-safe-parser/node_modules/postcss/package.json
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25 "name": "postcss",
26 "version": "8.2.6",
27 "description": "Tool for transforming styles with JS plugins",
28 "engines": {
29 "node": "^10 || ^12 || >=14"
30 },
31 "exports": {
32 ".": {
33 "require": "./lib/postcss.js",
34 "import": "./lib/postcss.mjs",
35 "types": "./lib/postcss.d.ts"
36 },
37 "./": "./"
38 },
39 "main": "./lib/postcss.js",
40 "types": "./lib/postcss.d.ts",
41 "keywords": [
42 "css",
43 "postcss",
44 "rework",
45 "preprocessor",
46 "parser",
47 "source map",
48 "transform",
49 "manipulation",
50 "transpiler"
51 ],
52 "funding": {
53 "type": "opencollective",
54 "url": "https://opencollective.com/postcss/"
55 },
56 "author": "Andrey Sitnik <andrey@sitnik.ru>",
57 "license": "MIT",
58 "homepage": "https://postcss.org/",
59 "repository": "postcss/postcss",
60 "dependencies": {
61 "colorette": "^1.2.1",
62 "nanoid": "^3.1.20",
63 "source-map": "^0.6.1"
64 },
65 "browser": {
66 "./lib/terminal-highlight": false,
67 "colorette": false,
68 "fs": false
69 }
70}
And this is what I get when I list the files in ./node_modules/postcss-safe-parser/node_modules/postcss/lib/
lgtd-lt-119-mbmt:frontend juliantc$ ls ./node_modules/postcss-safe-parser/node_modules/postcss/lib/
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25 "name": "postcss",
26 "version": "8.2.6",
27 "description": "Tool for transforming styles with JS plugins",
28 "engines": {
29 "node": "^10 || ^12 || >=14"
30 },
31 "exports": {
32 ".": {
33 "require": "./lib/postcss.js",
34 "import": "./lib/postcss.mjs",
35 "types": "./lib/postcss.d.ts"
36 },
37 "./": "./"
38 },
39 "main": "./lib/postcss.js",
40 "types": "./lib/postcss.d.ts",
41 "keywords": [
42 "css",
43 "postcss",
44 "rework",
45 "preprocessor",
46 "parser",
47 "source map",
48 "transform",
49 "manipulation",
50 "transpiler"
51 ],
52 "funding": {
53 "type": "opencollective",
54 "url": "https://opencollective.com/postcss/"
55 },
56 "author": "Andrey Sitnik <andrey@sitnik.ru>",
57 "license": "MIT",
58 "homepage": "https://postcss.org/",
59 "repository": "postcss/postcss",
60 "dependencies": {
61 "colorette": "^1.2.1",
62 "nanoid": "^3.1.20",
63 "source-map": "^0.6.1"
64 },
65 "browser": {
66 "./lib/terminal-highlight": false,
67 "colorette": false,
68 "fs": false
69 }
70}at-rule.d.ts css-syntax-error.d.ts input.d.ts map-generator.js postcss.d.ts processor.js rule.js tokenize.js
71at-rule.js css-syntax-error.js input.js node.d.ts postcss.js result.d.ts stringifier.js warn-once.js
72comment.d.ts declaration.d.ts lazy-result.d.ts node.js postcss.mjs result.js stringify.d.ts warning.d.ts
73comment.js declaration.js lazy-result.js parse.d.ts previous-map.d.ts root.d.ts stringify.js warning.js
74container.d.ts fromJSON.d.ts list.d.ts parse.js previous-map.js root.js symbols.js
75container.js fromJSON.js list.js parser.js processor.d.ts rule.d.ts terminal-highlight.js
76
ANSWER
Answered 2021-Nov-13 at 18:36I am also stuck with the same problem because I installed the latest version of Node.js (v17.0.1).
Just go for node.js v14.18.1
and remove the latest version just use the stable version v14.18.1
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25 "name": "postcss",
26 "version": "8.2.6",
27 "description": "Tool for transforming styles with JS plugins",
28 "engines": {
29 "node": "^10 || ^12 || >=14"
30 },
31 "exports": {
32 ".": {
33 "require": "./lib/postcss.js",
34 "import": "./lib/postcss.mjs",
35 "types": "./lib/postcss.d.ts"
36 },
37 "./": "./"
38 },
39 "main": "./lib/postcss.js",
40 "types": "./lib/postcss.d.ts",
41 "keywords": [
42 "css",
43 "postcss",
44 "rework",
45 "preprocessor",
46 "parser",
47 "source map",
48 "transform",
49 "manipulation",
50 "transpiler"
51 ],
52 "funding": {
53 "type": "opencollective",
54 "url": "https://opencollective.com/postcss/"
55 },
56 "author": "Andrey Sitnik <andrey@sitnik.ru>",
57 "license": "MIT",
58 "homepage": "https://postcss.org/",
59 "repository": "postcss/postcss",
60 "dependencies": {
61 "colorette": "^1.2.1",
62 "nanoid": "^3.1.20",
63 "source-map": "^0.6.1"
64 },
65 "browser": {
66 "./lib/terminal-highlight": false,
67 "colorette": false,
68 "fs": false
69 }
70}at-rule.d.ts css-syntax-error.d.ts input.d.ts map-generator.js postcss.d.ts processor.js rule.js tokenize.js
71at-rule.js css-syntax-error.js input.js node.d.ts postcss.js result.d.ts stringifier.js warn-once.js
72comment.d.ts declaration.d.ts lazy-result.d.ts node.js postcss.mjs result.js stringify.d.ts warning.d.ts
73comment.js declaration.js lazy-result.js parse.d.ts previous-map.d.ts root.d.ts stringify.js warning.js
74container.d.ts fromJSON.d.ts list.d.ts parse.js previous-map.js root.js symbols.js
75container.js fromJSON.js list.js parser.js processor.d.ts rule.d.ts terminal-highlight.js
76nvm uninstall <version>
77
OR
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25 "name": "postcss",
26 "version": "8.2.6",
27 "description": "Tool for transforming styles with JS plugins",
28 "engines": {
29 "node": "^10 || ^12 || >=14"
30 },
31 "exports": {
32 ".": {
33 "require": "./lib/postcss.js",
34 "import": "./lib/postcss.mjs",
35 "types": "./lib/postcss.d.ts"
36 },
37 "./": "./"
38 },
39 "main": "./lib/postcss.js",
40 "types": "./lib/postcss.d.ts",
41 "keywords": [
42 "css",
43 "postcss",
44 "rework",
45 "preprocessor",
46 "parser",
47 "source map",
48 "transform",
49 "manipulation",
50 "transpiler"
51 ],
52 "funding": {
53 "type": "opencollective",
54 "url": "https://opencollective.com/postcss/"
55 },
56 "author": "Andrey Sitnik <andrey@sitnik.ru>",
57 "license": "MIT",
58 "homepage": "https://postcss.org/",
59 "repository": "postcss/postcss",
60 "dependencies": {
61 "colorette": "^1.2.1",
62 "nanoid": "^3.1.20",
63 "source-map": "^0.6.1"
64 },
65 "browser": {
66 "./lib/terminal-highlight": false,
67 "colorette": false,
68 "fs": false
69 }
70}at-rule.d.ts css-syntax-error.d.ts input.d.ts map-generator.js postcss.d.ts processor.js rule.js tokenize.js
71at-rule.js css-syntax-error.js input.js node.d.ts postcss.js result.d.ts stringifier.js warn-once.js
72comment.d.ts declaration.d.ts lazy-result.d.ts node.js postcss.mjs result.js stringify.d.ts warning.d.ts
73comment.js declaration.js lazy-result.js parse.d.ts previous-map.d.ts root.d.ts stringify.js warning.js
74container.d.ts fromJSON.d.ts list.d.ts parse.js previous-map.js root.js symbols.js
75container.js fromJSON.js list.js parser.js processor.d.ts rule.d.ts terminal-highlight.js
76nvm uninstall <version>
77nvm uninstall v17.0.1
78
then install the LTS
one which is v14.18.1
1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6 throw e;
7 ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10 at new NodeError (node:internal/errors:371:5)
11 at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12 at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13 at resolveExports (node:internal/modules/cjs/loader:482:36)
14 at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15 at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16 at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17 at Module.require (node:internal/modules/cjs/loader:999:19)
18 at require (node:internal/modules/cjs/helpers:102:18)
19 at Object.<anonymous> (/Users/juliantc/Desktop/ai- studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25 "name": "postcss",
26 "version": "8.2.6",
27 "description": "Tool for transforming styles with JS plugins",
28 "engines": {
29 "node": "^10 || ^12 || >=14"
30 },
31 "exports": {
32 ".": {
33 "require": "./lib/postcss.js",
34 "import": "./lib/postcss.mjs",
35 "types": "./lib/postcss.d.ts"
36 },
37 "./": "./"
38 },
39 "main": "./lib/postcss.js",
40 "types": "./lib/postcss.d.ts",
41 "keywords": [
42 "css",
43 "postcss",
44 "rework",
45 "preprocessor",
46 "parser",
47 "source map",
48 "transform",
49 "manipulation",
50 "transpiler"
51 ],
52 "funding": {
53 "type": "opencollective",
54 "url": "https://opencollective.com/postcss/"
55 },
56 "author": "Andrey Sitnik <andrey@sitnik.ru>",
57 "license": "MIT",
58 "homepage": "https://postcss.org/",
59 "repository": "postcss/postcss",
60 "dependencies": {
61 "colorette": "^1.2.1",
62 "nanoid": "^3.1.20",
63 "source-map": "^0.6.1"
64 },
65 "browser": {
66 "./lib/terminal-highlight": false,
67 "colorette": false,
68 "fs": false
69 }
70}at-rule.d.ts css-syntax-error.d.ts input.d.ts map-generator.js postcss.d.ts processor.js rule.js tokenize.js
71at-rule.js css-syntax-error.js input.js node.d.ts postcss.js result.d.ts stringifier.js warn-once.js
72comment.d.ts declaration.d.ts lazy-result.d.ts node.js postcss.mjs result.js stringify.d.ts warning.d.ts
73comment.js declaration.js lazy-result.js parse.d.ts previous-map.d.ts root.d.ts stringify.js warning.js
74container.d.ts fromJSON.d.ts list.d.ts parse.js previous-map.js root.js symbols.js
75container.js fromJSON.js list.js parser.js processor.d.ts rule.d.ts terminal-highlight.js
76nvm uninstall <version>
77nvm uninstall v17.0.1
78nvm install --lts
79
This worked for me.
QUESTION
Babel and Node - No stack trace on syntax errors
Asked 2022-Jan-10 at 06:29I am converting a project over from using gulp to using nodemon so that I can use ES6 with babel. I'm following a pretty simple procedure to do so, which is well described here. A quick look at my package.json:
1{
2 "main": "index.js",
3 "scripts": {
4 "start": "FORCE_COLOR=3 nodemon --exec babel-node index.js"
5 },
6 "dependencies": {
7 "deps": "1.1.1"
8 },
9 "devDependencies": {
10 "@babel/cli": "^7.16.0",
11 "@babel/core": "^7.16.5",
12 "@babel/node": "^7.16.5",
13 "@babel/polyfill": "^7.12.1",
14 "@babel/preset-env": "^7.16.5",
15 "nodemon": "^2.0.15"
16 },
17 "babel": {
18 "presets": [
19 [
20 "@babel/preset-env",
21 {
22 "targets": {
23 "node": "current"
24 }
25 }
26 ]
27 ]
28 }
29}
30
When I run npm start
, nodemon runs the app, and reruns on save, but it crashes with a syntax error:
1{
2 "main": "index.js",
3 "scripts": {
4 "start": "FORCE_COLOR=3 nodemon --exec babel-node index.js"
5 },
6 "dependencies": {
7 "deps": "1.1.1"
8 },
9 "devDependencies": {
10 "@babel/cli": "^7.16.0",
11 "@babel/core": "^7.16.5",
12 "@babel/node": "^7.16.5",
13 "@babel/polyfill": "^7.12.1",
14 "@babel/preset-env": "^7.16.5",
15 "nodemon": "^2.0.15"
16 },
17 "babel": {
18 "presets": [
19 [
20 "@babel/preset-env",
21 {
22 "targets": {
23 "node": "current"
24 }
25 }
26 ]
27 ]
28 }
29}
30[nodemon] starting `babel-node index.js`
31[HPM] Proxy created: /auth -> http://localhost:8081/
32/myproject/node_modules/@babel/core/lib/parser/index.js:93
33 throw err;
34 ^
35
36SyntaxError: Legacy octal literals are not allowed in strict mode. (38:46)
37 at Parser._raise (/myproject/node_modules/@babel/parser/src/parser/error.js:147:45)
38 at Parser.raiseWithData (/myproject/node_modules/@babel/parser/src/parser/error.js:142:17)
39 at Parser.raise (/myproject/node_modules/@babel/parser/src/parser/error.js:91:17)
40 at Parser.recordStrictModeErrors (/myproject/node_modules/@babel/parser/src/tokenizer/index.js:1444:12)
41 at Parser.readNumber (/myproject/node_modules/@babel/parser/src/tokenizer/index.js:1239:12)
42 at Parser.getTokenFromCode (/myproject/node_modules/@babel/parser/src/tokenizer/index.js:951:14)
43 at Parser.nextToken (/myproject/node_modules/@babel/parser/src/tokenizer/index.js:307:10)
44 at Parser.next (/myproject/node_modules/@babel/parser/src/tokenizer/index.js:169:10) {
45 loc: Position { line: 38, column: 46 },
46 pos: 933,
47 code: 'BABEL_PARSE_ERROR',
48 reasonCode: 'StrictOctalLiteral'
49}
50[nodemon] app crashed - waiting for file changes before starting...
51
There doesn't seem to be a stack trace to the place in my code where this error is happening. I managed to track it down with some careful understanding of the no octal error, but other errors that come up look very similar, with no stack trace to the place in my own code where the error occurs. How can I debug like that? Is there a way to configure babel to include the origin of the error from my code?
ANSWER
Answered 2022-Jan-08 at 02:48It could potentially be that there is something wrong with the package itself. But babel is a properly and well maintained project so it could be something on your end
The error here is that leading zeros aren't allowed. Try and remove any instance of hard-coded leading zeros and then use +number
or parseInt
on any numbers which the values you won't know, such as from an API, reading from a database, or receiving user input.
QUESTION
Automatic detection of object property type based on another property value
Asked 2021-Dec-08 at 14:04I am trying to make a 'switcher' of an unknown type coming from a database. Basically, there are certain calculation types that have a different data structure and need to be processed differently depending on the type. My first way to solve the problem was using conditionals:
1type CalculationTypes = "add" | "average"
2
3export interface Calculation<T extends CalculationTypes> {
4 calculationID: string // unique to all calculations
5 type: T
6 payload: T extends "add" ? CalculationAdd : CalculationAverage
7}
8
9interface CalculationAdd {
10 addlist: {referenceContainer: string, referenceID: string}[]
11}
12
13interface CalculationAverage {
14 averageList: number[]
15}
16
This worked - kind of - because the type wasn't being detected later in the script. I had to infer it, which isn't so bad, but I'm sure there's a better way to do it where the transpiler can automatically deduce the type...
Then later in the script:
1type CalculationTypes = "add" | "average"
2
3export interface Calculation<T extends CalculationTypes> {
4 calculationID: string // unique to all calculations
5 type: T
6 payload: T extends "add" ? CalculationAdd : CalculationAverage
7}
8
9interface CalculationAdd {
10 addlist: {referenceContainer: string, referenceID: string}[]
11}
12
13interface CalculationAverage {
14 averageList: number[]
15}
16 for (const calculation of dbresult.calculations) {
17 switch(calculation.type) {
18 case "add":
19 const payload = calculation.payload as CalculationAdd // <--- this is what I want it to do automatically.
20 /** The transpiler does not detect it. It thinks that payload is of
21 type CalculationAdd | CalculationAverage **/
22 payload.addList // do stuff works now with type inference
23 // do more stuff
24 break;
25 case "average":
26 const payload = calculation.payload as CalculationAverage
27 payload.averageList // do stuff
28 // do more stuff
29 break;
30 }
31 }
32
Without type inference, typescript gives me the error:
1type CalculationTypes = "add" | "average"
2
3export interface Calculation<T extends CalculationTypes> {
4 calculationID: string // unique to all calculations
5 type: T
6 payload: T extends "add" ? CalculationAdd : CalculationAverage
7}
8
9interface CalculationAdd {
10 addlist: {referenceContainer: string, referenceID: string}[]
11}
12
13interface CalculationAverage {
14 averageList: number[]
15}
16 for (const calculation of dbresult.calculations) {
17 switch(calculation.type) {
18 case "add":
19 const payload = calculation.payload as CalculationAdd // <--- this is what I want it to do automatically.
20 /** The transpiler does not detect it. It thinks that payload is of
21 type CalculationAdd | CalculationAverage **/
22 payload.addList // do stuff works now with type inference
23 // do more stuff
24 break;
25 case "average":
26 const payload = calculation.payload as CalculationAverage
27 payload.averageList // do stuff
28 // do more stuff
29 break;
30 }
31 }
32Property 'addList' does not exist on type 'CalculationAdd | CalculationAverage'.
33 Property 'addList' does not exist on type 'CalculationAverage'
34
So for some reason, typescript has not deduced that it has to be of type CalculationAdd without type inference, even though that's the only possibility given the conditional I set up in the Calculation interface.
How can I change the way I'm defining these types and interfaces so that typescript automatically deduces them?
Thanks!
ANSWER
Answered 2021-Dec-08 at 14:04Typescript is actually capable of doing this. See this explanation, I think it's very similar with your use-case.
I think your problem comes from the fact that you've defined the same variable payload
in both switch-case branches. Either try to rename the payload
in the second case, or just wrap your switch-case branches in curly brackets, { ... }
.
Here's the code that works for me:
1type CalculationTypes = "add" | "average"
2
3export interface Calculation<T extends CalculationTypes> {
4 calculationID: string // unique to all calculations
5 type: T
6 payload: T extends "add" ? CalculationAdd : CalculationAverage
7}
8
9interface CalculationAdd {
10 addlist: {referenceContainer: string, referenceID: string}[]
11}
12
13interface CalculationAverage {
14 averageList: number[]
15}
16 for (const calculation of dbresult.calculations) {
17 switch(calculation.type) {
18 case "add":
19 const payload = calculation.payload as CalculationAdd // <--- this is what I want it to do automatically.
20 /** The transpiler does not detect it. It thinks that payload is of
21 type CalculationAdd | CalculationAverage **/
22 payload.addList // do stuff works now with type inference
23 // do more stuff
24 break;
25 case "average":
26 const payload = calculation.payload as CalculationAverage
27 payload.averageList // do stuff
28 // do more stuff
29 break;
30 }
31 }
32Property 'addList' does not exist on type 'CalculationAdd | CalculationAverage'.
33 Property 'addList' does not exist on type 'CalculationAverage'
34
35for (const calculation of dbresult.calculations) {
36 switch (calculation.type) {
37 case "add": {
38 const {payload} = calculation; // <--- automatically inferred by TS
39 payload.addlist // do stuff works now with type inference
40 console.log(payload);
41 break;
42 }
43 case "average": {
44 const {payload} = calculation;
45 payload.averageList // do stuff
46 console.log(payload);
47 break;
48 }
49 }
50}
51
QUESTION
What are all the ways you can encounter an EmptyStatement in a JavaScript AST?
Asked 2021-Nov-22 at 03:15I am writing a JS transpiler and need to know what I will encounter. I have handled almost every edge case except for the obscure EmptyStatement
. One place I encounter it is here:
1for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
2
The AST looks like this:
1for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
2{
3 "type": "Program",
4 "body": [
5 {
6 "type": "BlockStatement",
7 "body": [
8 {
9 "type": "AssignmentExpression",
10 "left": {
11 "type": "Identifier",
12 "start": 4014,
13 "end": 4018,
14 "name": "arrL"
15 },
16 "right": {
17 "type": "MemberExpression",
18 "object": {
19 "type": "Identifier",
20 "start": 4021,
21 "end": 4024,
22 "name": "arr"
23 },
24 "property": {
25 "type": "Identifier",
26 "start": 4025,
27 "end": 4031,
28 "name": "length"
29 },
30 "computed": false
31 },
32 "operator": "="
33 },
34 {
35 "type": "WhileStatement",
36 "test": {
37 "type": "Literal",
38 "value": true,
39 "raw": "true"
40 },
41 "body": {
42 "type": "BlockStatement",
43 "body": [
44 {
45 "type": "IfStatement",
46 "test": {
47 "type": "UpdateExpression",
48 "argument": {
49 "type": "Identifier",
50 "start": 4033,
51 "end": 4037,
52 "name": "arrL"
53 },
54 "operator": "--",
55 "prefix": false
56 },
57 "consequent": {
58 "type": "BlockStatement",
59 "body": [
60 {
61 "type": "EmptyStatement",
62 "start": 4061,
63 "end": 4062
64 },
65 {
66 "type": "AssignmentExpression",
67 "left": {
68 "type": "MemberExpression",
69 "object": {
70 "type": "Identifier",
71 "start": 4041,
72 "end": 4044,
73 "name": "arr"
74 },
75 "property": {
76 "type": "Identifier",
77 "start": 4045,
78 "end": 4049,
79 "name": "arrL"
80 },
81 "computed": true
82 },
83 "right": {
84 "type": "Identifier",
85 "start": 4054,
86 "end": 4060,
87 "name": "baseIn"
88 },
89 "operator": "*="
90 }
91 ]
92 },
93 "alternate": {
94 "type": "BlockStatement",
95 "body": [
96 {
97 "type": "BreakStatement"
98 }
99 ]
100 }
101 }
102 ]
103 }
104 }
105 ]
106 }
107 ]
108}
109
I don't even know what that EmptyStatement
is referencing yet haha. What are the other cases where you run into EmptyStatement
?
ANSWER
Answered 2021-Nov-22 at 03:15If you look closely at that for
statement, you'll see that it's body consists only of ;
. That's an empty statement. You'd get the same effect with, say,
1for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
2{
3 "type": "Program",
4 "body": [
5 {
6 "type": "BlockStatement",
7 "body": [
8 {
9 "type": "AssignmentExpression",
10 "left": {
11 "type": "Identifier",
12 "start": 4014,
13 "end": 4018,
14 "name": "arrL"
15 },
16 "right": {
17 "type": "MemberExpression",
18 "object": {
19 "type": "Identifier",
20 "start": 4021,
21 "end": 4024,
22 "name": "arr"
23 },
24 "property": {
25 "type": "Identifier",
26 "start": 4025,
27 "end": 4031,
28 "name": "length"
29 },
30 "computed": false
31 },
32 "operator": "="
33 },
34 {
35 "type": "WhileStatement",
36 "test": {
37 "type": "Literal",
38 "value": true,
39 "raw": "true"
40 },
41 "body": {
42 "type": "BlockStatement",
43 "body": [
44 {
45 "type": "IfStatement",
46 "test": {
47 "type": "UpdateExpression",
48 "argument": {
49 "type": "Identifier",
50 "start": 4033,
51 "end": 4037,
52 "name": "arrL"
53 },
54 "operator": "--",
55 "prefix": false
56 },
57 "consequent": {
58 "type": "BlockStatement",
59 "body": [
60 {
61 "type": "EmptyStatement",
62 "start": 4061,
63 "end": 4062
64 },
65 {
66 "type": "AssignmentExpression",
67 "left": {
68 "type": "MemberExpression",
69 "object": {
70 "type": "Identifier",
71 "start": 4041,
72 "end": 4044,
73 "name": "arr"
74 },
75 "property": {
76 "type": "Identifier",
77 "start": 4045,
78 "end": 4049,
79 "name": "arrL"
80 },
81 "computed": true
82 },
83 "right": {
84 "type": "Identifier",
85 "start": 4054,
86 "end": 4060,
87 "name": "baseIn"
88 },
89 "operator": "*="
90 }
91 ]
92 },
93 "alternate": {
94 "type": "BlockStatement",
95 "body": [
96 {
97 "type": "BreakStatement"
98 }
99 ]
100 }
101 }
102 ]
103 }
104 }
105 ]
106 }
107 ]
108}
109if (a--);
110
although many style guides discourage that. {}
is a lot clearer, imho. That's an empty block, not an empty statement. {;}
would be a block consisting only of an empty statement, which is also pretty rare, but you might find something like :
1for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
2{
3 "type": "Program",
4 "body": [
5 {
6 "type": "BlockStatement",
7 "body": [
8 {
9 "type": "AssignmentExpression",
10 "left": {
11 "type": "Identifier",
12 "start": 4014,
13 "end": 4018,
14 "name": "arrL"
15 },
16 "right": {
17 "type": "MemberExpression",
18 "object": {
19 "type": "Identifier",
20 "start": 4021,
21 "end": 4024,
22 "name": "arr"
23 },
24 "property": {
25 "type": "Identifier",
26 "start": 4025,
27 "end": 4031,
28 "name": "length"
29 },
30 "computed": false
31 },
32 "operator": "="
33 },
34 {
35 "type": "WhileStatement",
36 "test": {
37 "type": "Literal",
38 "value": true,
39 "raw": "true"
40 },
41 "body": {
42 "type": "BlockStatement",
43 "body": [
44 {
45 "type": "IfStatement",
46 "test": {
47 "type": "UpdateExpression",
48 "argument": {
49 "type": "Identifier",
50 "start": 4033,
51 "end": 4037,
52 "name": "arrL"
53 },
54 "operator": "--",
55 "prefix": false
56 },
57 "consequent": {
58 "type": "BlockStatement",
59 "body": [
60 {
61 "type": "EmptyStatement",
62 "start": 4061,
63 "end": 4062
64 },
65 {
66 "type": "AssignmentExpression",
67 "left": {
68 "type": "MemberExpression",
69 "object": {
70 "type": "Identifier",
71 "start": 4041,
72 "end": 4044,
73 "name": "arr"
74 },
75 "property": {
76 "type": "Identifier",
77 "start": 4045,
78 "end": 4049,
79 "name": "arrL"
80 },
81 "computed": true
82 },
83 "right": {
84 "type": "Identifier",
85 "start": 4054,
86 "end": 4060,
87 "name": "baseIn"
88 },
89 "operator": "*="
90 }
91 ]
92 },
93 "alternate": {
94 "type": "BlockStatement",
95 "body": [
96 {
97 "type": "BreakStatement"
98 }
99 ]
100 }
101 }
102 ]
103 }
104 }
105 ]
106 }
107 ]
108}
109if (a--);
110if (debugging) {
111 /* Commented out for now */ ;
112}
113
So, what's an empty statement? It's a statement with nothing but a semicolon terminator. Empty, as it says.
It's interesting that the for
statement has already been desugared, which might be confusing. But it's correct; for(init; test; advance) body;
is semantically equivalent to
1for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
2{
3 "type": "Program",
4 "body": [
5 {
6 "type": "BlockStatement",
7 "body": [
8 {
9 "type": "AssignmentExpression",
10 "left": {
11 "type": "Identifier",
12 "start": 4014,
13 "end": 4018,
14 "name": "arrL"
15 },
16 "right": {
17 "type": "MemberExpression",
18 "object": {
19 "type": "Identifier",
20 "start": 4021,
21 "end": 4024,
22 "name": "arr"
23 },
24 "property": {
25 "type": "Identifier",
26 "start": 4025,
27 "end": 4031,
28 "name": "length"
29 },
30 "computed": false
31 },
32 "operator": "="
33 },
34 {
35 "type": "WhileStatement",
36 "test": {
37 "type": "Literal",
38 "value": true,
39 "raw": "true"
40 },
41 "body": {
42 "type": "BlockStatement",
43 "body": [
44 {
45 "type": "IfStatement",
46 "test": {
47 "type": "UpdateExpression",
48 "argument": {
49 "type": "Identifier",
50 "start": 4033,
51 "end": 4037,
52 "name": "arrL"
53 },
54 "operator": "--",
55 "prefix": false
56 },
57 "consequent": {
58 "type": "BlockStatement",
59 "body": [
60 {
61 "type": "EmptyStatement",
62 "start": 4061,
63 "end": 4062
64 },
65 {
66 "type": "AssignmentExpression",
67 "left": {
68 "type": "MemberExpression",
69 "object": {
70 "type": "Identifier",
71 "start": 4041,
72 "end": 4044,
73 "name": "arr"
74 },
75 "property": {
76 "type": "Identifier",
77 "start": 4045,
78 "end": 4049,
79 "name": "arrL"
80 },
81 "computed": true
82 },
83 "right": {
84 "type": "Identifier",
85 "start": 4054,
86 "end": 4060,
87 "name": "baseIn"
88 },
89 "operator": "*="
90 }
91 ]
92 },
93 "alternate": {
94 "type": "BlockStatement",
95 "body": [
96 {
97 "type": "BreakStatement"
98 }
99 ]
100 }
101 }
102 ]
103 }
104 }
105 ]
106 }
107 ]
108}
109if (a--);
110if (debugging) {
111 /* Commented out for now */ ;
112}
113{
114 init;
115 while(true) {
116 if (test) {
117 body;
118 advance;
119 }
120 else
121 break;
122 }
123}
124
Apparently, even though it desugared the for
statement, it preserved the empty body. That might be in order to have a place to hang the line number, or it might just be that it was easier to leave it at that point in the parse. The curious transformation of an (implicit) while (test) { ... }
into while (true) { if (test) { ... } else break; }
is probably to simplify decomposition into basic blocks, or to enable a standard optimization which reorders the code. Just guesses, though.
QUESTION
Regular expression to determine key
Asked 2021-Nov-18 at 14:59In my Angular application, I'm using a translation service that supports defining custom transpilers. The transpiler receives incoming translations based on the content in the translation files. Some are pure translations and you can also pass objects into translations (e.g. the label.profile.greeting
translation key):
1{
2 "label.startpage.welcome": "Welcome!",
3 "label.startpage.info": "This website is awesome. Hope you like it.",
4 "label.profile.greeting": "Hi, {{username}}."
5}
6
When the service tries to translate, it loops through all words within a translation and sends that word to the transpiler. The transpiler then tries to determine if it's a simple translation, or an object that needs to be injected into the translation.
My transpiler however has the ability to inject translations into other translations:
1{
2 "label.startpage.welcome": "Welcome!",
3 "label.startpage.info": "This website is awesome. Hope you like it.",
4 "label.profile.greeting": "Hi, {{username}}."
5}
6{
7 "label.favourite": "My favourite fruit is",
8 "label.favourite.banana": "{{label.favourite}} banana!",
9 "label.favourite.pineapple": "{{label.favourite}} pineapple!"
10}
11
I've written this simple arrow-function that my transpiler uses to determine if the incoming translation is a translation key or not:
1{
2 "label.startpage.welcome": "Welcome!",
3 "label.startpage.info": "This website is awesome. Hope you like it.",
4 "label.profile.greeting": "Hi, {{username}}."
5}
6{
7 "label.favourite": "My favourite fruit is",
8 "label.favourite.banana": "{{label.favourite}} banana!",
9 "label.favourite.pineapple": "{{label.favourite}} pineapple!"
10}
11const isTranslationKey = (value: string): boolean => /(\w+(?:\.\w+)+)/.test(value);
12
And it works. Although, this regular expression has a high security risk due to regexs security-sensetivity, according to SonarQube. I guess it's about the length of the string that may be the cause of future failures, since there's no maximum limit for the string. And I've tried to change the regex to something simular, but I can't judge if it's a better fit or not:
1{
2 "label.startpage.welcome": "Welcome!",
3 "label.startpage.info": "This website is awesome. Hope you like it.",
4 "label.profile.greeting": "Hi, {{username}}."
5}
6{
7 "label.favourite": "My favourite fruit is",
8 "label.favourite.banana": "{{label.favourite}} banana!",
9 "label.favourite.pineapple": "{{label.favourite}} pineapple!"
10}
11const isTranslationKey = (value: string): boolean => /(\w+(?:\.\w+)+)/.test(value);
12/^([A-Za-z]{1,10})+(\.([A-Za-z]{1,10})).{1,40}$/
13
I need some expertise on this matter. Thanks in advance! :)
ANSWER
Answered 2021-Nov-18 at 14:59The final regex you can use can be either of the two, depending on whether you need to support all Unicode letters or not:
1{
2 "label.startpage.welcome": "Welcome!",
3 "label.startpage.info": "This website is awesome. Hope you like it.",
4 "label.profile.greeting": "Hi, {{username}}."
5}
6{
7 "label.favourite": "My favourite fruit is",
8 "label.favourite.banana": "{{label.favourite}} banana!",
9 "label.favourite.pineapple": "{{label.favourite}} pineapple!"
10}
11const isTranslationKey = (value: string): boolean => /(\w+(?:\.\w+)+)/.test(value);
12/^([A-Za-z]{1,10})+(\.([A-Za-z]{1,10})).{1,40}$/
13/^(?=.{3,60}$)[a-z]+(?:\.[a-z]+)+$/i
14/^(?=.{3,60}$)\p{L}+(?:\.\p{L}+)+$/u
15
Note the second regex is ECMAScript 2018 compliant, and before using it make sure your JavaScript environment supports it.
Details:
^
- start of string(?=.{3,60}$)
- a positive lookahead that requires three to sixty chars other than line break chars followed with end of string position immediately to the right of the current location[a-z]+
- one or more ASCII letters (any Unicode letters if you use\p{L}
or\p{Alphabetic}
)(?:\.[a-z]+)+
- one or more repetitions of.
and one or more ASCII letters (any Unicode letters if you use\p{L}
/\p{Alphabetic}
)$
- end of string.
See the regex demo.
QUESTION
Vue project with or without Babel?
Asked 2021-Sep-19 at 18:11I am using Vue CLI to create a Vue 2.0 project and one of the options is using Babel. I understand Babel is a transpiler but what exactly does it do? I created a project with it and another without it and I don't see the difference so what exactly is the pro/con of it ? I can't see offhand what it is doing.
ANSWER
Answered 2021-Sep-19 at 18:11You are correct. Babel is a transpiler. It transpiles your JavaScript code to one or more taget browsers, that does not support the lastest fetures. You will not see any difference, if using a newer browser.
Babal usually only makes sense if you need to support older browsers, like IE 11 or browsers from before 2017.
QUESTION
What is the javascript find() function as opposed to the Array.find() method?
Asked 2021-Sep-04 at 03:31Obviously I know what Array.find()
is.
However, my transpiler emitted (in the search for an 'e' in a string):
1let /*integer*/ e = find(0X65,s);
2
but forgot to include my implementation of find()
, so now I'm curious as to what the original is.
Everything works once I added the include, I'm not asking how to find an e in a string.
Hovering over that find()
just says "native code". Google yields nothing but Array.find()
for me however there is no array and no dot, so what is it?
ANSWER
Answered 2021-Sep-03 at 22:28window.find()
is a nonstandard function that's nevertheless implemented in all browsers except Internet Explorer. It's apparently a programmatic way to invoke the browser's interactive Find
operation (i.e. Ctl-f).
QUESTION
Do functional language compilers optimize a "filter, then map" operation on lists into a single pass?
Asked 2021-Aug-17 at 13:19I mostly use TypeScript during my work day and when applying functional patterns I oftentimes see a pattern like:
1const someArray = anotherArray.filter(filterFn).map(transformFn)
2
This code will filter through all of anotherArray
's items and then go over the filtered list (which may be identical if no items are filtered) again and map things. In other words, we iterate over the array twice.
This behavior could be achieved with a "single pass" over the array with a reduce
:
1const someArray = anotherArray.filter(filterFn).map(transformFn)
2const someArray = anotherArray.reduce((acc, item) => {
3 if (filterFn(item) === false) {
4 return acc;
5 }
6 acc.push(item);
7 return acc;
8}, [])
9
I was wondering if such optimization is something the transpiler (in the TS world) knows to do automatically and whether such optimizations are automatically done in more "functional-first" languages such as Clojure or Haskell. For example, I know that functional languages usually do optimizations with tail recursion, so I was wondering also about the "filter then map" case. Is this something that compilers actually do?
ANSWER
Answered 2021-Aug-17 at 13:19First of all, you usually shouldn't obsess about getting everything into a single pass. On small containers there is not that much difference between running a single-operation loop twice and running a dual-operation loop once. Aim to write code that's easily understandable. One for loop might be more readable than two, but a reduce is not more readable than a filter then map.
What the compiler does depends on your "container." When your loop is big enough to care about execution time, it's usually also big enough to care about memory consumption. So filtering then mapping on something like an observable works on one element at a time, all the way through the pipeline, before processing the next element. This means you only need memory for one element, even though your observable could be infinite.
QUESTION
Best Practice: Enable React Component in User Input
Asked 2021-Aug-17 at 10:42I'd like to allow users of a blog like app written in rails/react/material-ui/mobx to add custom components like polls to their articles. So I'd like to add some kind of button to the article editor which adds a poll which will then be rendered using a custom react component when published. What is the best practice for doing this sort of thing? Should I?
Have the user input contain JSX code for that component, e.g., the saved text in the db would then look like
1some text....
2<MyPoll ...>
3 <MyChoice> Foo </MyChoice>
4</MyPoll>
5more text...
6
But I'd then need to have some function to interpret this code allowing only designated components (so like a on the fly jsx transpiler with sanitization..does this exist?).
Have a model for polls and in the editor create the poll object and then insert a div with a special class like "react-standin" and then have a table I consult which maps the unique div id to poll objects in database. So the saved text would look like:
1some text....
2<MyPoll ...>
3 <MyChoice> Foo </MyChoice>
4</MyPoll>
5more text...
6 some text....
7 <div class="react-standin" id=myguid></div>
8 more text...
9
And then when it comes time to display I'd map the id to whatever saved component needs to be displayed (drawback is I now need to implement backend support for each component and have ownership info so users can't guess at other user components).
Some kind of hybrid. For instance create some kind of DSL using properties of dom elements in the input, e.g., the saved text would look like:
1some text....
2<MyPoll ...>
3 <MyChoice> Foo </MyChoice>
4</MyPoll>
5more text...
6 some text....
7 <div class="react-standin" id=myguid></div>
8 more text...
9some text....
10<div class="poll-component" ...>
11 <div class="poll-answer"> Foo </div>
12</div>
13more text...
14
This feels rightish, especially if there is a library that enables this kind of translation of HTML element attributes to react components.
Something else? Maybe represent an article as an array of possible components one of which being raw text/html/markdown. So it would be saved on server as an array of guids referencing database components of different types (this seems wrong)
I feel like this must be a solved problem and I'd love to see how other people have handled this issue but I couldn't find it when I searched.
ANSWER
Answered 2021-Aug-17 at 10:42Ok, after banging my head against this for awhile I ended up searching for react based rich text editors. The two major editor frameworks here are slate.js and draft.js. Now what both these editor frameworks do is store your input as a tree (e.g. a JSON version of something like a DOM for the text) that captures any styling applied to the elements below.
These frameworks also allow you to define your own styling and you can simply style a poll element in your text editor using your react poll component. You can then simply display the result using a read only version of the text editor (or directly parse it out using react components).
However, if you want to store your user content as HTML or other standard markup rather than something like a JSON format linked to the particular editor config you've choosen then I still don't know.
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Transpiler
Tutorials and Learning Resources are not available at this moment for Transpiler