2

I run create-react-app then switch to directory and run npm start. Just wondering how I would specify a different file than index.js to start on the server

Here's my package.json file:

{
 "name": "todo",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
   "react": "^16.2.0",
   "react-dom": "^16.2.0",
   "react-scripts": "1.1.1"
 },
 "scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test --env=jsdom",
   "eject": "react-scripts eject"
 }
}

I tried changing:

"start": "react-scripts start",

to

"start": "node index.js",  or  "start": "node ./src/index.js",

but those don't work

DCR
  • 14,737
  • 12
  • 52
  • 115

2 Answers2

2

For now there is no argument for running different file.js in react. so you need to eject your react application by command

npm run eject

By running this you will have full control in your project. Then you need to modify some code in your config/paths.js

module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp(buildPath),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  //appIndexJs: resolveModule(resolveApp, 'src/index'),
  appIndexJs: resolveModule(resolveApp, 'src/'+ process.argv[process.argv.length-1]),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/setupTests'),
  proxySetup: resolveApp('src/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  swSrc: resolveModule(resolveApp, 'src/service-worker'),
  publicUrlOrPath,
};

Take a note on these lines:

//appIndexJs: resolveModule(resolveApp, 'src/index'),
appIndexJs: resolveModule(resolveApp, 'src/'+ process.argv[process.argv.length-1]),

src/index mean npm start will run your application with src/index.js. So by changing the code you can pass argument with new file name for example

npm start -- foo

So your application will run with new file in src/foo.js. Normaly your argument is last item. If code is not working you can try to print all arguments by

// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
Piseth Sok
  • 1,789
  • 1
  • 20
  • 24
1

Find and edit package.json file. For example:

{
  "name": "build",
  "version": "0.0.1",
  "scripts": {
    "start": "node different-file.js"
  }
}
Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37