By default, Next.js uses next.config.js file for configuration.
How do you change that to something like my.next.config.js?
After digging it is not currently possible (Feb 2023) to change location of next.config.js, but if you want to fully customize contents of the config you can build this yourself:
// next.config.js
const actualConfig = process.env.NEXT_CONFIG_LOCATION
module.exports = require(actualConfig)
Then pass NEXT_CONFIG_LOCATION=./my.next.config.js to next.js commands (NEXT_CONFIG_LOCATION in this case is just an example).
Related
I am creating a web component in Node.js. This component uses images, which I have put in a sub-directory within the component's directory.
When I import the image I get the error "Failed to load resource: the server responded with a status of 404 (Not Found)" in Chromium. I understand that the browser wants me to use the path from the root of the project to the file, but it kind of defeats the purpose of having a nice directory structure.
I also have Snowpack installed.
Edit: Using the Node.js package path is difficult, since Snowpack can't normally use packages not inside the browser, and I have to use Snowpack. With devOptions { polyfillNode: true } it should be possible, but I tried creating a snowpack.config.js file with that line to no avail. How do I implement it?
Or how do you usually handle paths in Snowpack? I am unsure about using a polyfill, and if there is another solution, I'd be happy to try it.
Relative paths can be used as :
//in ./app.js
const path = require('path');
//using path.relative()
const greet = require(path.relative(__dirname, './lib/greet.js'));
Same for image
// get the relative path of the image file from this file
const imagePath = path.relative(__dirname, './public/image.jpg');
// export a function that returns an HTML string with the image tag
module.exports = function() {
return `<img src="${imagePath}" alt="Image">`;
};
I'm trying to build my Next.js project but it keeps giving me this error in the terminal:
Error: Build optimization failed: found page without a React Component as default export in
pages/components/context/Context
That's the React context API file, there isn't supposed to be any default export there. Is this a bug or what?
You should move your components outside the pages folder. pages/ should only be used for page components as Next.js routing is based on its structure.
Next.js has a file-system based router built on the concept of pages.
When a file is added to the pages directory it's automatically available as a route.
By default, Next.js assumes anything under the pages folder is a page component and will try to build each file as a page.
Even though the above is the default behaviour, you can configure your Next.js app to include non-page files in the pages directory.
To do so, you can modify the pageExtensions entry in the next.config.js file as shown below. Then rename your page components to have a file extension that includes .page (_document.page.js, _app.page.js, index.page.js, etc).
module.exports = {
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}
With this configuration, Next.js will ignore any file that doesn't contain .page for the purpose of building pages/API routes and routing.
In my case, I had an empty file index.js in a folder. Using Nextjs Default Router
It seems to be not declared default export keyword in context component.
Try it as follow:
const Context = ()=>{
...
}
export default Context
I had the same error.
If you comment out all other code but leave this NextJS won't get mad at you:
export default function Home1() {
return <>{/* nothing */}</>;
}
I like to keep older index files and components locally and on github so this is a nice hack. I just copy all of the existing code add it to a new file and then add 1 to it for example:
index1.js
You can also leave a comment to kind of bring you and other devs up to speed as to why you did this for example:
//good for history of index implementation and associated syntax logic
I have a CRA fresh project, this project is going to be used on a site that renders multiple plugins inside an "iframe", serving them using a proxy which I can't figure out the URL before instantiating the plugin.
To get the location of the plugin, they provide us with a function called getOriginProxyUrl() that returns us a path name (something like /plugins/plugin-name/random-code-ID/random-domain/).
My issue comes during the load of react chunks under this configuration, index.html loads correctly, but bundle.js & chunks[..].js files returns me a 404 since the URL is trying to point to /static/js/... instead of /plugins/plugin-name/random-code-ID/random-domain/static/js/...
Since I'm using CRA, I investigated and I found that setting an .env variable called PUBLIC_URL would help me to set this URL correctly, I tested it by hardcoding the publicpath that getOriginProxyUrl() function returns and it allowed me to use my React application in their "iframe" without issues.
My question is, Is there a way to set this PUBLIC_URL during runtime (Perhaps in the index.html file) instead of setting an .env file or env variable?
I tried also setting __webpack_public_path__ as described in Change Webpack's publicPath on the fly, but it only allowed me to change the URL of the assets (images & icons) and didn't work for the static chunks
I hope that my questions is clear enough to describe my issue hehe, Thank you in advance!
I think its better to use environment and use process.env in the webpack as global variable and use it in the output object of your webpack config
const ASSET_PATH = process.env.ASSET_PATH || '/';
export default {
output: {
publicPath: ASSET_PATH,
},
plugins: [
// This makes it possible for us to safely use env vars on our code
new webpack.DefinePlugin({
'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH),
}),
],
};
Or on the fly
__webpack_public_path__ = process.env.ASSET_PATH;
Have a look at the following
react env
Nginx compatible solution
I am trying to use create-react-app to create a simple web-app. I have moved the pages and components into separate directories under src labeled pages and components. I would like to change/add the entry point for index.js from src/index.js to src/pages/index.js. Another option would be to keep index.js in src/ and import from pages and component directories. Can someone help me to find how i can change the entry point path?
I can't seem to find the location of the default html-webpack-plugin config file.
Here is what I would like the structure to be:
(in src)
...
pages/
- App.js
- Home.js
components/
- Filter.js
serviceWorker.js
I used react-rewired to achieve something like this:
https://github.com/timarney/react-app-rewired/issues/189
in my config-overrides.js
console.log("#######################");
console.log("# using react-rewired #");
console.log("#######################");
module.exports = {
// The Webpack config to use when compiling your react app for development or production.
webpack: function(config, env) {
// ...add your webpack config
console.log("###########");
console.log("# webpack #");
console.log("###########");
console.log({config, env});
if (env === 'development') {
config.entry = config.entry.replace(new RegExp("index.ts$"), 'runApp.tsx');
console.log("entry point changed:", config.entry);
}
return config;
},
}
I needed to run on a different file but only when running the development server
the link above has the full solution
Try using npm run eject.
this will take all script from node_module/react-script in the project folder. There you will be able to access webpack.config.js file in config folder. you can search for html-webpack-plugin and get the access point.
I have added my access point to config/paths.js and used as default access point which worked for me.
NOTE: make sure you don't have any different configuration setting as it gets very difficult to manage, if environment setup changes or doesn't match.
I am trying to set some environment variables (for making API calls to dev/prod endpoints, keys depending on dev/prod, etc.) and I'm wondering if using dotenv will work.
I've installed dotenv, and I am using webpack.
My webpack entry is main.js, so in this file I've put require('dotenv').config()
Then, in my webpack config, I've put this:
new webpack.EnvironmentPlugin([
'NODE_ENV',
'__DEV_BASE_URL__' //base url for dev api endpoints
])
However, it is still undefined. How can I do this correctly?
Sorry for picking up old question, but
react-scripts actually uses dotenv library under the hood.
With react-scripts#0.2.3 and higher, you can work with environment variables this way:
create .env file in the root of the project
set environment variables starting with REACT_APP_ there
access it by process.env.REACT_APP_... in components
.env
REACT_APP_BASE_URL=http://localhost:3000
App.js
const BASE_URL = process.env.REACT_APP_BASE_URL;
See docs for more details.
The short answer is no. A browser cannot access local or server environment variables so dotenv has nothing to look for. Instead, you specify ordinary variables in your React application, usually in a settings module.
Webpack can be made to take environment variables from the build machine and bake them into your settings files. However, it works be actually replacing strings at build-time, not run-time. So each build of your application will have the values hard-coded into it. These values would then be accessible through the process.env object.
var nodeEnv = process.env.NODE_ENV;
Additionally, you could use the DefinePlugin for webpack which lets you explicitly specify different values depending on your build target (dev, prod, etc.). Note that you have to JSON.stringify all values passed into it.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
This is fine for any sort of public details but should never be used for any sort of private keys, passwords or API secrets. This is because any values baked in are publicly accessible and could be used maliciously if they contain sensitive details. For those sorts of things, you need to write some server-side code and build a simple API which can authenticate with the 3rd party API using the secrets, then pass the relevant details along to your client-side application. Your server-side API acts as an intermediary, protecting your secrets while still getting the data you need.
Create .env file
API_URL=http://localhost:8000
Install dotenv npm package
$ npm install --save-dev dotenv
Config webpack to add env variables
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
plugins: [
new webpack.DefinePlugin(envKeys)
]
};
Great job! Enjoy React and dotenv.
Actually, you can use dotenv in your React app with webpack. Moreover, there are several ways of doing it. However, keep in mind that it's still a build-time configuration.
A similar way to the answer above. You import dotenv in your webpack config and use DefinePlugin to pass the variables to your React app. More complete guide on how you can inject your .env files depending on current configuration could be found in this blog.
Using a dotenv-webpack plugin. I personally find it really convenient. Let's say you have environments: dev, staging and prod. You create .env file for each environment (.env.dev, .env.staging, etc). In your webpack configuration you need to pick a correct file for the environment:
const Dotenv = require('dotenv-webpack');
module.exports = (env, argv) => {
const envPath = env.ENVIRONMENT ? `.env.${env.ENVIRONMENT}` : '.env';
const config = {
...
plugins: [
new Dotenv({
path: envPath
})
]
};
return config;
};
When you build the app for a particular environment, just pass the environment name to webpack:
webpack --config webpack.config.js --env.ENVIRONMENT=dev
I Just created a config.json in the source folder:
{
"api_url" : "http://localhost:8080/"
}
then required it in the file I needed it
const config = require('./config.json');
and used config.api_url