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'
Related
Why base url and paths work on normal React but not on React Native??
This is my tsconfig file:
{
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"components/*": ["./components/*"],
"assets/*": ["./assets/*"],
"screens/*": ["./screens/*"],
"navigation/*": ["./navigation/*"],
"api/*": ["./api/*"],
"utils/*": ["./utils/*"],
"#shared/*": [
"../shared/*"
]
}
},
"include": [
"./*"
],
"extends": "expo/tsconfig.base"
}
From App.tsx I tried to import AppNav component from "navigation/AppNav" but it gives error that "Unable to resolve module navigation/AppNav"
I even tried to install modeule-resolver plugin for babel but it didnt work:
module.exports = function(api) {
api.cache(false);
return {
presets: ['babel-preset-expo'],
plugins: [
"nativewind/babel",
[
"module-resolver",
{
"root": ["./"],
"alias": {
"components/*": "components/*",
"assets/*": "assets/*",
"screens/*": "screens/*",
"navigation/*": "navigation/*",
"api/*": "api/*",
"utils/*": "utils/*",
}
}
]
],
};
};
I tried with regex expression but still didnt work
module.exports = function(api) {
api.cache(false);
return {
presets: ['babel-preset-expo', "module:metro-react-native-babel-preset"],
plugins: [
"nativewind/babel",
[
"module-resolver",
{
"root": ["."],
"alias": {
"components/(.+)": "./components/\\1",
"assets/(.+)": "./assets/*",
"screens/(.+)": "./screens/*",
"navigation/(.+)": "./navigation/\\1",
"api/(.+)": "./api/*",
"utils/(.+)": "./utils/*",
}
}
]
],
};
};
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
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
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
I have reactjs + typescript web application which suppose to use opencv.js library for doing some vision tasks. However I can't make intellisense to work in my Visual Studio Code IDE for that library. I load library as following
var CV = require('../opencvLibs/build_js/bin/opencv_js.js');
class InnerApp extends React.Component{
componentDidMount(){
CV["onRuntimeInitialized"]= () => {
let mat = new CV.Mat();
console.log(mat.size());
mat.delete();
}
}
render(){
return(
<Provider rootStore = {new RootStore()}>
<App/>
</Provider>
)
}
}
ReactDOM.render(
<Provider>
<InnerApp />
</Provider>,
document.getElementById('root'));
As you can see I am logging into console empty mat size just to check if library is working fine and I am getting width and height logged properly which indicates that library is loaded successfully.
I tried to add jsconfig.json file as I saw that as potential solution in official Visual Studio Code docs, however that didn't work.
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"esModuleInterop": true,
"removeComments": true,
"preserveConstEnums": true,
"jsx": "react",
"sourceMap": true,
"experimentalDecorators": true,
"lib": ["es6","dom"],
"typeRoots": [
"typings",
"node_modules/#types"
]
},
"files":[
"opencvLibs/build_js_wasm/bin/opencv.js"
]
}
jsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs"
},
"exclude": [
"node_modules",
"**/node_modules/*"
],
"include": [
"opencvLibs/build_js/bin/opencv.js"
],
"typeAcquisition": {
"include": [
"opencvLibs/build_js/bin/opencv.js"
]
}
}
webpack.dev.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const HOST = process.env.HOST || '127.0.0.1';
const PORT = process.env.PORT || '9000';
const config = {
mode: 'development',
entry: {
app: './src/index.tsx',
},
output: {
path: path.resolve(__dirname, '../dist'),
filename: '[name].bundle.js'
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: 'eval-cheap-module-source-map',
module: {
rules: [{
test: /\.tsx?$/,
use: [{
loader: 'ts-loader',
options: {
onlyCompileBundledFiles: true,
}
}]
},
{
test: /\.(s?)css$/,
use: ['style-loader','css-loader','sass-loader']
},
{
test: /\.otf$/,
use: {
loader: 'file-loader',
options: {
name: 'dist/fonts/[name].[ext]'
}
}
},
{
//test: /\.(png|jpe?g|gif|svg)$/
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
use: [{
loader: 'url-loader',
//loader: 'url?limit=100000&name=[name].[ext]',
options: {
limit: 8192
}
}]
},
],
},
devServer: {
host: HOST,
port: PORT,
compress: true,
inline: true,
historyApiFallback: true,
hot: true,
overlay: true,
open: true,
},
plugins: [
new webpack.LoaderOptionsPlugin({
options:{
scripts: [
"../opencvLibs/build_js_wasm/bin/opencv.js"
]}
}),
new webpack.HotModuleReplacementPlugin({
}),
new HtmlWebpackPlugin({
template: 'src/index.html',
title: 'React Mobx Starter',
inject: 'body'
}),
],
node: {
fs: 'empty'
},
};
module.exports = config;
Expected result would be that intellisense works when I type "CV."
Thanks for your help!