define is not defined while build nextjs app - reactjs

i'm using next version 10.0.1, and react 17.0.2,
When i'm trying build my next app, i get an error:
ReferenceError: define is not defined
at Object.<anonymous> (/Users/***/Desktop/gm/toesim-web/node_modules/#glonassmobile/codebase-web/createAction.js:1:1)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.i1ag (/Users//Desktop/gm/toesim-web/.next/server/pages/deeplink/payment/[paymentId].js:7425:18)
at __webpack_require__ (/Users/Desktop/gm/toesim-web/.next/server/pages/deeplink/payment/[paymentId].js:23:31)
at Object.S/7G (/Users/Desktop/gm/toesim-web/.next/server/pages/deeplink/payment/[paymentId].js:5128:21) {
type: 'ReferenceError'
}
this is the code from node_modules where error is occurred
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.createAction = void 0;
var createAction = function (type, payload) { return ({ type: type, payload: payload }); };
exports.createAction = createAction;
});
//# sourceMappingURL=createAction.js.map
i try to add to my next.config file
require('amd-loader') but it doesnt work too
i was looking for answer around a week, but it all was useless
could somebody give a help?
PS next.config.js
const path = require('path');
const withCSS = require('#zeit/next-css');
const withSass = require('#zeit/next-sass');
const webpack = require('webpack');
const ES6Promise = require("es6-promise");
ES6Promise.polyfill();
if (typeof define !== 'function') {
var define = require('amdefine')(module); // this doesn't work too
}
module.exports = withCSS(withSass({
webpack: function (config, options) {
config.plugins.push(new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Promise: 'es6-promise-promise',
}))
config.module.rules.push(
{
test: /.(js|jsx|tsx|ts)$/,
exclude: /node_modules/,
include: path.resolve('./client/pages/'),
use: {
loader: "ts-loader",
options: {
configFile: './src/client/app/tsc.json',
},
},
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use:{
loader: 'url-loader',
options: {
name: '[name].[ext]',
limit: 10000000,
esModule : false,
}
}
},
)
return config
}
}))
and tsconfig
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES6",
"moduleResolution": "Node",
"sourceMap": true,
"module": "commonjs",
"jsx": "preserve",
"allowJs": true,
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"baseUrl": "./src/client/",
"isolatedModules": true
},
"files": [
"./src/pages/index.tsx"
],
"include": [
"src/**/*.ts",
"src/**/*.tsx",
],
"exclude": [
"src/**/*.proto",
"node_modules"
]
}```

Probably you are trying to import some library on server which require browser environment
looking from the error trace its /node_modules/#glonassmobile/codebase-web/createAction.js:1:1
If you decide to use this library, you need to check if you are server or client side like const isServer = typeof window === 'undefined', and import the library only in case you are client side

Related

Migrating NextJS#11 to NextJS#12 with SWC config

I'm trying to migrate my NextJS App to version 12.
it's working properly using babel config, but I like to change the environment to swc.
I have the error below during production build:
./src/pages/_app.tsx Module not found: Can't resolve
'#styles/index.scss' in
'/project/src/pages'
these are my config files:
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"#assets/*": ["src/assets/*"],
"#api": ["src/api"],
"#i18n": ["src/scripts/i18n"],
"#styles": ["./src/styles"],
"#redux": ["./src/redux"],
"#slices/*": ["./src/redux/slices/*"],
"#utils": ["./src/utils"],
"#root/*": ["./src/root/*"],
"#hooks/*": ["./src/hooks/*"],
"#schema/*": ["./src/types/schema/*"],
"#configs": ["./src/app.config"],
"#contexts/*": ["./src/contexts/*"],
"#components/*": ["./src/components/*"],
"#extensions/*": ["./src/scripts/extensions/*"],
"~menu/*": ["./src/sections/menu/*"],
"~order/*": ["./src/sections/order/*"],
"~search/*": ["./src/sections/search/*"],
"~growth/*": ["./src/sections/growth/*"],
"~army/*": ["./src/sections/army/*"],
"#jest-provider": ["./src/root/JestProvider"],
"~service/*": ["./src/service/*"]
}
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.test.js"]
}
next.config.js
const webpack = require('webpack')
const withPWA = require('next-pwa')
const pJson = require('./package.json')
const withPlugins = require('next-compose-plugins')
const setupENVs = require('./src/scripts/env.config')
const bundleAnalyzer = require('#next/bundle-analyzer')
const routesConfig = require('./src/scripts/routes.config')
const runtimeCaching = require('./src/scripts/sw.cache.config')
const {withSentryConfig} = require('#sentry/nextjs')
// const withTM = require('next-transpile-modules')(['design-system'])
const isDev = process.env.NODE_ENV !== 'production'
routesConfig(isDev)
const plugins = [new webpack.DefinePlugin(setupENVs())]
const securityHeaders = [
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN',
},
]
const basConfig = (nextConfig = {}) => ({
...nextConfig,
webpack(config, options) {
config.plugins.push(...plugins)
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options)
}
return config
},
})
const withAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})
let transpileModules
if (isDev) {
transpileModules = basConfig()
} else if (process.env.ANALYZE === 'true') {
transpileModules = basConfig(withAnalyzer())
} else {
transpileModules = basConfig(
withPWA({pwa: {dest: 'public', runtimeCaching, disable: true}})
)
}
const moduleExports = withPlugins([transpileModules], {
compiler: {
styledComponents: {
displayName: true,
ssr: true,
},
removeConsole: true,
// reactRemoveProperties: true,
},
env: {
APP_VERSION: pJson.version,
},
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders,
},
]
},
sentry: {
disableClientWebpackPlugin: true,
disableServerWebpackPlugin: true,
},
swcMinify: true,
experimental: {
forceSwcTransforms: true,
swcTraceProfiling: true,
swcMinifyDebugOptions: {
compress: {
defaults: true,
side_effects: false,
},
},
modularizeImports: {
lodash: {
transform: 'lodash/{{member}}',
},
},
},
})
module.exports = withSentryConfig(moduleExports)
babel.config.json
{
"presets": [
[
"next/babel",
{
"preset-env": {}
}
]
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
[
"module-resolver",
{
"root": "./src",
"alias": {
"#assets": "./src/assets",
"#api": "./src/api",
"#i18n": "./src/scripts/i18n",
"#root": "./src/root",
"#styles": "./src/styles",
"#redux": "./src/redux",
"#slices": "./src/redux/slices",
"#hooks": "./src/hooks",
"#utils": "./src/utils",
"#schema": "./src/types/schema",
"#contexts": "./src/contexts",
"#configs": "./src/app.config",
"#components": "./src/components",
"#extensions": "./src/scripts/extensions",
"~menu": "./src/sections/menu",
"~order": "./src/sections/order",
"~search": "./src/sections/search",
"~growth": "./src/sections/growth",
"~army": "./src/sections/army",
"#jest-provider": "./src/root/JestProvider",
"#mockData": "./__mocks__/data",
"~service": "./src/service"
},
"extensions": [".js", ".jsx", ".ts", ".tsx", ".es", ".es6", ".mjs"]
}
]
],
"env": {
"production": {
"plugins": [["transform-remove-console"]]
},
"test": {
"presets": [["#babel/preset-env", {"modules": false}], "next/babel"]
}
}
}
could you please help me on this?
You should consider these two things.
First, as the next.js document says you're opting out the swc compiler by having babel config.
The new Rust compiler is backwards compatible. If you have an existing Babel configuration, you will automatically be opted out.
here's the document: https://nextjs.org/blog/next-12#faster-builds-and-fast-refresh-with-rust-compiler
Second, you have some issues with your module mapping as the styles must not be under the 'pages' folder.
'/project/src/pages'

How to declare and use a local component as module?

I export const FontXLarge = 18; in ThemeFont.ts.
When I want to use it, I used to use import {FontXLarge} from '../theme/ThemeFont';
After I add
{
"name": "theme"
}
I can use import {FontXLarge} from 'theme/ThemeFont'; but I can't link to the folder.
So I think that if I declare module 'ThemeFont' I can link it. And the fact that I did it. When I ctrl + click (or alt + click in VSCode, depending on your setting), it can open the file ThemeFont.ts when I use import {FontXLarge} from 'ThemeFont';
declare module 'ThemeFont' {
export const FontXLarge = 18;
}
When hover, it will show like that
But it shows error when build: Unable to resolve module ThemeFont in node_modules
We can use this library to declare local component https://github.com/tleunen/babel-plugin-module-resolver
My config for it:
create/edit: tsconfig.json
{
"compilerOptions": {
"skipLibCheck": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "./app",
"paths": {
"#/*": ["./*"]
},
"outDir": "../dst/",
"typeRoots": ["node_modules/#types"]
},
"lib": ["es2016"],
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
create/edit jsconfig.json
{
"compilerOptions": {
"paths": {
"#/*": [
"./app/*"
]
}
}
}
create/edit jsconfig.js
System.config({
paths: {
'#/*': './app/*',
},
})
edit babel.config.js
const presets = ['module:metro-react-native-babel-preset'];
const plugins = [
[
'react-native-reanimated/plugin',
// {
// globals: ['__scanQRCodes', '__decode'],
// },
],
[
'module-resolver',
{
root: ['./app'],
extensions: ['.js', '.json'],
alias: {
'#': './app',
},
},
],
];
const env = {
production: {
plugins: ['react-native-paper/babel'],
},
};
module.exports = {
presets,
plugins,
env,
};
Now you can use
import {FontXLarge} from '#/Theme/ThemeFont';
remember that after config it, resetting app cache:
yarn start --reset-cache

Background classes and custom theme don't work in Tailwind CSS with React

I am currently working on a project with ReactJS, Typescript and TailwindCSS and everything seems to be working properly. The point is, all TailwindCSS classes work just fine except the ones for the background. Whenever I use a class like,bg-sky-500 or bg-slate-500, the color never displays and the background remains as it is. Also, I have tried to set a custom theme inside tailwindcss.config.json, but it didn't work either. Here are the configs used in the project:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "src",
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
tailwind.config.ts
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
postcss.config.ts
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
main.ts
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
"#storybook/preset-create-react-app",
],
framework: "#storybook/react",
core: {
builder: "#storybook/builder-webpack5",
},
webpackFinal: async (config) => {
config.module.rules.push({
test: /\,css&/,
use: [
{
loader: "postcss-loader",
options: {
ident: "postcss",
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
preview.ts
import "index.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
index.css
#tailwind base;
#tailwind components;
#tailwind utilities;
#tailwind forms;
Would anyone be able to help with this?
The "sky" and "slate" colors only became available in Tailwind CSS version 3+. I would recommend upgrading to the latest for these colors and the many additional improvements.
If you are stuck with v2, you should reference the list of colors in the old documentation: https://v2.tailwindcss.com/docs/background-color
Alternatively, you can add these colors in your tailwind.config.js file in the theme section, copying the values from Tailwind 3+:
module.exports = {
theme: {
extend: {
colors: {
slate: {
50: "rgb(248 250 252)",
100: "rgb(241 245 249)",
...
},
sky: {
50: "rgb(240 249 255)",
100: "rgb(224 242 254)",
...
},
},
},
},
}
See: https://v2.tailwindcss.com/docs/customizing-colors

Bundle Webpack React library as an ESM module - Object.defineProperty called on non-object

I need to publish a single package that can be imported as default (or named as last resort) by multiple projects.
After hundreds of issues trying to do this with Rollup I moved on to trying to bundle my library with Webpack. My package only exports one default.
I have another project that is importing the package as default that I have been testing with, it's intended that it should return the root React component which is default exported.
I have tried bundling with UMD, which doesn't crash my external project but doesn't return an exported default or named export anywhere.
If I set my Webpack config to bundle ESM instead I get an obscure vague error regarding Object.defineProperty.
If somebody has ESM bundling working in Webpack 5 please help, or any ideas that have worked for you
Uncaught TypeError: Object.defineProperty called on non-object
at Function.defineProperty (<anonymous>)
at Function.__webpack_require__.r (build.js:13594)
at eval (index.js:1)
at Object.../discover-v2/dist/index.js (build.js:10623)
at __webpack_require__ (build.js:13402)
at fn (build.js:13671)
at eval (index.tsx:20)
at Module../src/views/Discovers/Discover/index.tsx (build.js:5141)
at __webpack_require__ (build.js:13402)
at fn (build.js:13671)
This points to a webpack function:
/* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
webpack.config.ts:
module.exports = {
entry: './src/package.tsx',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
library: {
// name: 'discover',
type: 'module',
},
libraryTarget: 'module',
module: true,
},
experiments: {
asset: true,
outputModule: true,
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
//TODO waiting on https://github.com/dividab/tsconfig-paths-webpack-plugin/issues/61
// eslint-disable-next-line #typescript-eslint/ban-ts-comment
//#ts-ignore
plugins: [new TsconfigPathsPlugin()],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
exclude: [/node_modules/, nodeModulesPath],
},
{
test: /\.(png|jpg|mov|mp4)$/,
loader: 'url-loader',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader'],
},
{
test: /\.svg$/,
use: ['#svgr/webpack', 'url-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new webpack.DefinePlugin({
'process.env.LOCAL': JSON.stringify(process.env.LOCAL),
'process.env.STAGING': JSON.stringify(process.env.STAGING),
'process.env.API_URL': JSON.stringify(process.env.API_URL),
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.NAME': JSON.stringify(pkg.name),
'process.env.VERSION': JSON.stringify(pkg.version),
}),
new ForkTsCheckerWebpackPlugin({
eslint: {
files: './src/**/*.{ts,tsx,js,jsx}', // required - same as command `eslint ./src/**/*.{ts,tsx,js,jsx} --ext .ts,.tsx,.js,.jsx`
},
}),
new CleanWebpackPlugin(),
],
};
.babelrc
{
"presets": [
["#babel/env", { "modules": false }],
"#babel/react",
"#babel/typescript",
[
"#emotion/babel-preset-css-prop",
{
"autoLabel": "always",
"sourceMap": true,
"labelFormat": "[local]"
}
]
],
"plugins": [
"#babel/transform-runtime",
"#babel/proposal-class-properties",
"#babel/proposal-object-rest-spread"
]
}
Root component - src/package.tsx
const RootProvider: React.FC<RootProps> = ({ assets, ...props }) => (
<StoreProvider store={store}>
<ConnectedRouter history={history}>
<AssetsContext.Provider value={assets}>
<Root {...props} />
</AssetsContext.Provider>
</ConnectedRouter>
</StoreProvider>
);
export default RootProvider;
export { RootProvider as discover };
package.json main/module
{
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
...
tsconfig.json
{
"compilerOptions": {
"typeRoots": ["src/#types", "node_modules/#types"],
"sourceMap": true,
"noImplicitAny": false,
"module": "esnext",
"target": "es5",
"lib": ["esnext", "dom", "dom.iterable"],
"removeComments": true,
"allowSyntheticDefaultImports": true,
"jsx": "react-jsx",
"jsxImportSource": "#emotion/react",
"allowJs": true,
"baseUrl": "./",
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"downlevelIteration": true,
"paths": {
...
},
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist",
"declarationDir": ".",
"preserveConstEnums": true,
"declaration": true // generates .d.ts files inside the output directory
},
"include": ["./src", "./webpack.config.ts", "./webpack.package.config.ts"],
"exclude": ["dist"]
}
Bundle dist/index.js output exports (added default and named to test)
var __webpack_exports__ = __webpack_require__("./src/package.tsx");
var __webpack_exports__default = __webpack_exports__.default;
var __webpack_exports__discover = __webpack_exports__.discover;
export { __webpack_exports__default as default, __webpack_exports__discover as discover };
My consuming project that is importing the package has a similar webpack (without the library config, including aliases to fix multiple react errors when testing packaged project with yarn link), with an exact same .babelrc and tsconfig.json (with path changes)
alias: {
...
// bypass multiple react versions issue when testing internal packages
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom'),
'#emotion/react': path.resolve('./node_modules/#emotion/react'),
'#material-ui/core': path.resolve('./node_modules/#material-ui/core')
}
From my research, it is related to eval-* devtool in webpack config.
https://github.com/webpack/webpack/issues/11277#issuecomment-724024303
A workaround would be to set it (for the project importing that package) to false or change it to something other than eval-* according to docs: https://webpack.js.org/configuration/devtool/

How to make a declared module visible in Enzyme shallow render?

I've been trying to figure out how to have my declared module be found when I shallow render a component using enzyme in my jest unit tests. I have a custom declared module like so:
// index.d.ts
declare module "_aphrodite" {
import {StyleDeclarationValue} from "aphrodite";
type CSSInputType = StyleDeclarationValue | false | null | void;
interface ICSSInputTypesArray extends Array<CSSInputTypes> {}
export type CSSInputTypes = CSSInputType | CSSInputType[] | ICSSInputTypesArray;
}
Which is used by a component of mine called closeButton:
// closeButton.tsx
import {CSSInputTypes} from "_aphrodite";
export interface ICloseButtonProps {
onClick: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
cssStyles?: CSSInputTypes;
}
#injectable()
#observer
#autobind
export class CloseButton extends React.Component<ICloseButtonProps> {
// implementation
}
And a simple unit test that shallow renders a component:
// closeButton.test.tsx
import {shallow} from "enzyme";
import {CloseButton} from "../../common";
import * as React from "react";
describe("Common - Close Button", () => {
it("Shallow Render", () => {
const component = shallow(<CloseButton onClick={null}/>);
console.log(component);
});
});
When I run the test, I get the following error:
Which is strange because the closeButton class doesn't throw any compilation errors and maps the module fine. Same goes with when I run my project locally, it doesn't throw any run time error about not being able to find the _aphrodite module. It seems it's just with testing that this comes up.
Now I've tried to change various settings in my jest.config.json, tsconfig.json, and webpack.config.js settings with no luck. I'm hoping someone with more experience than I would know what needs to be done in order to make my _aphrodite module found when running a shallow render on a component.
Below are the settings for the aforementioned files:
// jest.config.json
{
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|svg)$": "<rootDir>/src/components/__tests__/_transformers/fileTransformer.js"
},
"transform": {
"\\.(ts|tsx)$": "ts-jest"
},
"setupFiles": [
"<rootDir>/src/components/__tests__/setup.ts"
],
"testRegex": "(/__tests__/\\.*|(\\.|/)(test))\\.tsx?$",
"testURL": "http://localhost/",
"collectCoverage": false,
"timers": "fake"
}
// tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build/",
"sourceMap": true,
"noImplicitAny": true,
"module": "esnext",
"target": "es2018",
"jsx": "react",
"watch": false,
"removeComments": true,
"preserveConstEnums": true,
"inlineSourceMap": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": [
"dom",
"dom.iterable",
"es2018",
"esnext"
],
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"isolatedModules": false
},
"include": [
"./src/**/*"
],
"exclude": [
"./node_modules"
]
}
// webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');
const dotenv = require('dotenv');
const fs = require('fs'); // to check if the file exists
module.exports = () => {
return {
plugins: []
};
};
/**
* DevServer
*/
const devServer = {
inline: true,
host: "localhost",
port: 3000,
stats: "errors-only",
historyApiFallback: true,
watchOptions: {
poll: true
},
};
module.exports.getEnv = () => {
// Create the fallback path (the production .env)
const basePath = __dirname + '/.env';
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + ".local";
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// call dotenv and it will return an Object with a parsed key
const finalEnv = dotenv.config({path: finalPath}).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(finalEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(finalEnv[next]);
return prev;
}, {});
return new webpack.DefinePlugin(envKeys);
};
/**
* Plugins
*/
const plugins = [
new HtmlWebpackPlugin({
template: "./index.html"
}),
module.exports.getEnv()
];
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/build",
publicPath: "/"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{test: /\.tsx?$/, loader: "ts-loader"},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{enforce: "pre", test: /\.js$/, loader: "source-map-loader", exclude: [/node_modules/, /build/, /__test__/]},
{test:/\.css$/, use:['style-loader','css-loader'] },
{test:/\.(png|svg)$/, loader: "url-loader"},
{test:/\.mp3$/, loader: "url-loader" }
]
},
plugins: plugins,
devServer: devServer,
mode: "development",
performance: {
hints: false
}
};
And here is my project structure:
Feel free to ask if more information is needed.
Turns out I just needed to add it to the list of setup files in jest.config.json
// jest.config.json
"setupFiles": [
"<rootDir>/src/components/__tests__/setup.ts",
"<rootDir>/src/aphrodite/index.ts"
],

Resources