Rollup Build failure for SCSS exports to be used in TS ( [!] Error: 'default' is not exported by src/styles/variables.scss ) - reactjs

I'm running into the following rollup build failure where I would like to be able to used exports from a scss file in my typescript files.
The build failure reads as follows:
[!] Error: 'default' is not exported by src/styles/variables.scss,
imported by src/components/Layout/Layout.themes.tsx
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src/components/Layout/Layout.themes.tsx (1:7) 1: import vbl from
'../../styles/variables.scss';
My rollup config looks as follows:
import scss from 'rollup-plugin-scss';
import typescript from 'rollup-plugin-typescript2';
import image from '#rollup/plugin-image';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';
export default {
input: ['src/index.tsx'],
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true,
name: 'Main'
},
{
file: pkg.module,
format: 'esm',
sourcemap: true,
name: 'tree-shaking'
}
],
external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
plugins: [image(), scss({ output: 'dist/styles.css' }), typescript({ useTsconfigDeclarationDir: true }), terser()]
};
The variables.scss contains:
// colors
$color-blue: #1c4077;
$color-orange: #e87d1e;
:export {
colorBlue: $color-blue;
colorOrange: $color-orange;
}
The variables.scss.d.ts typings file contains:
export interface IGlobalScss {
colorBlue: string;
colorOrange: string;
}
export const variables: IGlobalScss;
export default variables;
And the Layout.themes.tsx file reads as follows:
import vbl from '../../styles/variables.scss';
export const myTheme = {
headerColor: vbl.colorBlue,
footerColor: vbl.colorOrange
}
I've tried an import of the non-default export import { variables } from '../../styles/variables.scss'; but it fails as well with:
[!] Error: 'variables' is not exported by src/styles/variables.scss,
imported by src/components/Layout/Layout.themes.tsx
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src/components/Layout/Layout.themes.tsx (1:9) 1: import {
variables } from '../../styles/variables.scss';
I am able to serve the project via Storybook, however when I build via Rollup I encounter the error listed above. Please assist me in resolving this build failure?
Here is a CodeSandbox for this example. Extract the zip, yarn and run either yarn start or yarn build to test in VSCode. You'll notice that yarn start succeeds whereas yarn build will fail as mentioned above.

I think the problem is that the output property is not false.
Here is what the plugin does when that property is set to false:
if (options.output === false) {
const css = compileToCSS(code)
return {
code: 'export default ' + JSON.stringify(css),
map: { mappings: '' }
}
}
and this happens in the transform hook, which is invoked before the parsing takes place. This is important because export default ... is treated as a module, meaning you can import it in your js files.
So I think you'll have to manually bundle that variables file with:
scss({ output: false }).
Now, another problem arises: when you import from the .scss file, you'll get the :export object stringified.
For example:
"export default ":export {\n colorBlue: #1c4077;\n colorOrange: #e87d1e; }\n""
the plugin in use does not seem to handle this case.
So I think the solution involves manipulating that string so that you'd end up with something like this:
`{ colorX: 'value', colorY: 'value' }`

Related

Cypress headless - no loaders are configured to process png files

I am trying to run cypress test cases headless using cmd command
npx cypress run
But it gives me below error -
Do I need to install any dependency for this to load.
Even css files are not getting loaded.
Note : I haven't installed webpack or any other dependency. Only cypress is installed additionally.
Yes, you will need to extend the webpack configuration used by cypress to handle the files you would like to load. You can find an example here
Below I've modified the example to work with cypress 10.
// cypress.config.ts
import { defineConfig } from 'cypress';
import findWebpack from 'find-webpack';
import webpackPreprocessor from '#cypress/webpack-preprocessor';
const webpackOptions = findWebpack.getWebpackOptions();
const options = {
webpackOptions,
watchOptions: {},
};
export default defineConfig({
e2e: {
setupNodeEvents(on) {
// implement node event listeners here
// on('file:preprocessor', webpack(options));
// use a module that carefully removes only plugins
// that we found to be breaking the bundling
// https://github.com/bahmutov/find-webpack
const cleanOptions = {
reactScripts: true,
};
findWebpack.cleanForCypress(cleanOptions, webpackOptions);
on('file:preprocessor', webpackPreprocessor(options));
},
specPattern: 'src/**/*.cy.{js,jsx,ts,tsx}',
},
});

Vitejs | Uncaught Error: Dynamic require of "<path>.svg" is not supported

I'm trying to use react-flagpack in my project that uses Vite, but whenever I use it i get the following error:
Uncaught Error: Dynamic require of "node_modules/flagpack-core/dist/flags/cDBuMQWP.svg" is not supported
Is this an issue with Vite? or am I doing something wrong.
Thanks in advance!
As of June 14th 2021 it's now supported. :3
Can you check if this works? I don't know if it will for react-flagpack; this is likely a require statement that is breaking the build... I found a solution using #originjs/vite-plugin-commonjs, which I posted here.
First install the package:
yarn add #originjs/vite-plugin-commonjs -D
or
npm i #originjs/vite-plugin-commonjs -D
And then, in your vite.config file:
import { defineConfig } from 'vite';
import { viteCommonjs, esbuildCommonjs } from '#originjs/vite-plugin-commonjs';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
viteCommonjs(),
],
optimizeDeps: {
esbuildOptions: {
plugins: [
// Solves:
// https://github.com/vitejs/vite/issues/5308
esbuildCommonjs(['react-flagpack'])
],
},
},
});
Then, try loading your file normally. This worked for me using tiny-react-slider which was using a require statement for a .css file

React with TypeScript using tsyringe for dependency injection

I am currently having trouble with my React TypeScript project.
I created my project with npx create-react-app my-app --template typescript.
I recently added tsyringe for dependency injection and was trying to implement it for an apiService. After following the readme(https://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection) for adding primitive values I have hit a block. I already add experimentalDecorators and emitDecoratorMetadata to my tsconfig.json file with no success.
The error actual error I am encountering is:
./src/ts/utils/NetworkService.ts 9:14
Module parse failed: Unexpected character '#' (9:14)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
| let NetworkService = (_dec = singleton(), _dec(_class = (_temp = class NetworkService {
> constructor(#inject('SpecialString')
| value) {
| this.str = void 0;
I am fairly sure this problem is caused by Babel, however I created this with npm create react-app --template typescript and do not seem to have access to the Babel configuration.
NetworkService.ts
#singleton()
export default class NetworkService
{
private str: string;
constructor(#inject('SpecialString') value: string) {
this.str = value;
}
}
Invocation method
bob()
{
const inst = container.resolve(NetworkService);
}
Registering Class in index.ts
container.register('SpecialString', {useValue: 'https://myme.test'});
#registry([
{ token: NetworkService, useClass: NetworkService },
])
class RegisterService{}
React-Scripts manages many of the configs related to the project. For many cases, this is fine and actually a nice feature. However, because React-Scripts uses Babel for it's development environment and does not expose the config.
You have to run npm run eject to expose the configurations.
Please note, this is a one-way operation and can not be undone.
Personally, I prefer more control with my configuration.
After this you can edit the webpack.config.js in the newly created config folder.
Find the section related to the babel-loader in the dev-environment and add 'babel-plugin-transform-typescript-metadata' to the plugins array.
Expanding on Jordan Schnur's reply, here are some more pitfalls I encountered when adding TSyringe to my CRA app:
Use import type with #inject
If you get this error "TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled." replace import with import type for the offending imports. You will encounter this when working with #inject
E.g. replace import { IConfig } from "iconfig" with import type { IConfig } from "iconfig"
Fixing Jest
Your Jest tests will also break with TSyringe, especially when using #inject. I got the error "Jest encountered an unexpected token" with details constructor(#((0, _tsyringe.inject)("")) ("#" marked as the offending token). I took the following steps to fix that in CRA:
Add the line import "reflect-metadata"; to the top of the file src/setupTests.ts
In config/jest/babelTransform.js replace line 18 and following:
From
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});
to:
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
require.resolve('babel-plugin-transform-typescript-metadata')
],
babelrc: false,
configFile: false,
});
Instead of eject, you may use a lib that "overrides" some of your params.
I used craco : https://www.npmjs.com/package/#craco/craco
I've created an simpler DI library that doesn't need decorators or polyfill. Works with CRA like a charm and has cool React bindings
iti
import { useContainer } from "./_containers/main-app"
function Profile() {
const [auth, authErr] = useContainer().auth
if (authErr) return <div>failed to load</div>
if (!auth) return <div>loading...</div>
return <div>hello {auth.profile.name}!</div>
}

How to import a json file in typescript? [duplicate]

I have a JSON file that looks like following:
{
"primaryBright": "#2DC6FB",
"primaryMain": "#05B4F0",
"primaryDarker": "#04A1D7",
"primaryDarkest": "#048FBE",
"secondaryBright": "#4CD2C0",
"secondaryMain": "#00BFA5",
"secondaryDarker": "#009884",
"secondaryDarkest": "#007F6E",
"tertiaryMain": "#FA555A",
"tertiaryDarker": "#F93C42",
"tertiaryDarkest": "#F9232A",
"darkGrey": "#333333",
"lightGrey": "#777777"
}
I'm trying to import it into a .tsx file. For this I added this to the type definition:
declare module "*.json" {
const value: any;
export default value;
}
And I'm importing it like this.
import colors = require('../colors.json')
And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:
Property 'primaryMain' does not exist on type 'typeof "*.json"
With TypeScript 2.9.+ you can simply import JSON files with benefits like typesafety and intellisense by doing this:
import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);
Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):
"resolveJsonModule": true,
"esModuleInterop": true,
Side notes:
Typescript 2.9.0 has a bug with this JSON feature, it was fixed with 2.9.2
The esModuleInterop is only necessary for the default import of the colorsJson. If you leave it set to false then you have to import it with import * as colorsJson from '../colors.json'
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json have a single export named default.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain declared by your "*.json".
All of this assumes that your module loader is providing the JSON as the default export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
Here's how to import a json file at runtime
import fs from 'fs'
var dataArray = JSON.parse(fs.readFileSync('data.json', 'utf-8'))
This way you avoid issues with tsc slowing down or running out of memory when importing large files, which can happen when using resolveJsonModule.
It's easy to use typescript version 2.9+. So you can easily import JSON files as #kentor decribed.
But if you need to use older versions:
You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts location is the same as with the include property in your tsconfig.json file.
If you don't have an include property in your tsconfig.json file. Then your folder structure should be like that:
- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts
But if you have an include property in your tsconfig.json:
{
"compilerOptions": {
},
"exclude" : [
"node_modules",
"**/*spec.ts"
], "include" : [
"src/**/*"
]
}
Then your typings.d.ts should be in the src directory as described in include property
+ node_modules/
- package.json
- tsconfig.json
- src/
- app.ts
- typings.d.ts
As In many of the response, You can define a global declaration for all your JSON files.
declare module '*.json' {
const value: any;
export default value;
}
but I prefer a more typed version of this. For instance, let's say you have configuration file config.json like that:
{
"address": "127.0.0.1",
"port" : 8080
}
Then we can declare a specific type for it:
declare module 'config.json' {
export const address: string;
export const port: number;
}
It's easy to import in your typescript files:
import * as Config from 'config.json';
export class SomeClass {
public someMethod: void {
console.log(Config.address);
console.log(Config.port);
}
}
But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json configuration:
{
"name" : "some project",
"scripts": {
"build": "rm -rf dist && tsc && cp src/config.json dist/"
}
}
In my case I needed to change tsconfig.node.json:
{
"compilerOptions": {
...
"resolveJsonModule": true
},
"include": [..., "colors.json"]
}
And to import like that:
import * as colors from './colors.json'
Or like that:
import colors from './colors.json'
with "esModuleInterop": true
You should add
"resolveJsonModule": true
as part of compilerOptions to tsconfig.json.
Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.
Example #
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
// .ts
import settings from "./settings.json";
settings.debug === true; // OK
settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number
// settings.json
{
"repo": "TypeScript",
"dry": false,
"debug": false
}
by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
Another way to go
const data: {[key: string]: any} = require('./data.json');
This was you still can define json type is you want and don't have to use wildcard.
For example, custom type json.
interface User {
firstName: string;
lastName: string;
birthday: Date;
}
const user: User = require('./user.json');
In an Angular (typescript) app, I needed to include a .json file in my environment.ts. To do so, I had to set two options in tsconfig:
{
"compilerOptions": {
"moduleResolution": "node",
"resolveJsonModule": true
}
}
Then, I could import my json file into the environment.ts:
import { default as someObjectName } from "../some-json-file.json";
You can import a JSON file without modifying tsconfig you tell explicitly that you are importing JSON
import mydata from './mydataonfile.json' assert { type: "json" };
I know this does not fully answer the question but many people come here to know how to load JSON directly from a file.
Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:
const config = require('./config.json');
Note that if you using #kentor ways
Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):
You need to add --resolveJsonModule and--esModuleInterop behind tsc command to compile your TypeScript file.
Example:
tsc --resolveJsonModule --esModuleInterop main.ts
require is a common way to load a JSON file in Node.js
in my case I had to change: "include": ["src"] to "include": ["."] in addition to "resolveJsonModule":true because I tried to import manifest.json from the root of the project and not from ./src

Module not found: Error: Can't resolve 'zlib'

I am trying to migrate a CRA react application to NX, following steps on the official site
When I hit nx serve
I am facing the following error:
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/png-js/dist/png-js.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\png-js\dist'
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/pdfkit/dist/pdfkit.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\pdfkit\dist'
Knowing that: before I start migration my project worked fine.
npm version: 6.14.11
node version: 14.16.0
I've tried to hit npm install zlib yet I get
Cannot find module './zlib_bindings'
For some reason, VSCode inserted import e from 'express' at the top of my file in react
import { response } from 'express';
I delete the above import line and then the problem is resolved, all the errors are gone after the above change.
It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.
Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "#nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".
Content for webpack.config.js:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
node: undefined
};
};
So, this config change makes webpack correctly understand what polyfills are needed.
Alternatively, you can do the following:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'),
}
}
};
};
For me it was the code:
import { response } from 'express'
This was entered automatically by VSCode at the beginning of the file.
Deleting it solved the problem.
In my case was because I tried to type 'Text' and suddenly, the autocomplete added me this line on top:
import { text } from 'express';
Just deleted it and it worked fine.
Go Search Icon in VSCode search "express" you may get things like
import { text } from 'express'
import { Router } from 'express'
import { X,Y,Z } from 'express'
delete this line your app will work fine

Resources