47ndr
47ndr

Reputation: 633

Import a NPM module with a Nuxt Application in it

I would like to develop an NPM module that the user can import in his project. The module contain a full administration panel created with Nuxt. I don't want the user know anything about Nuxt, he just need to run a command like:

myppcommand start

and the application starts a server that is running the administration panel.

So my idea is to develop the NPM module with Nuxt. Generate all the static file inside ./dist folder and then myappcommand start will serve the app from node_modules.

// NPM Package myapp
// nuxt.config.js

export default {
    components: [
        {
            path: '~/components/',
            extensions: ['vue']
        }
    ],
    buildDir: './.nuxt',
    srcDir: './src/',
    target: 'static',
    ssr: false,
    generate: {
        dir: './dist/'
    }
};
// NPM Package myapp
npx nuxt generate

The command will generate all files in ./dist folder.

// User repo
npm install myapp

This will install myapp inside ./node_modules.

// User repo
cd node_modules/myapp/ && npx nuxt start -c nuxt.config.js

This will start the server and serve the app.

But is this the best way possible? It seems a bit hacky to me, to go inside node_modules, does somebody know a better way?

Upvotes: 0

Views: 861

Answers (1)

RWD
RWD

Reputation: 1326

You could achieve this by declaring that your package has an executable file which starts Nuxt, in the bin property of package.json.

Firstly, create an executable script to start the app:

bin/start.js


    #!/usr/bin/env node

    // Based on node_modules/.bin/nuxt

    global.__NUXT_PATHS__ = (global.__NUXT_PATHS__ || []).concat(__dirname)
    
    require('@nuxt/cli').run(['start'])
      .catch((error) => {
        require('consola').fatal(error)
        process.exit(2)
      })
      

You can verify that this starts the app by running ./bin/start.js (provided you have made the file executable), or node ./bin/start.js.

Then, declare that your package should install this as a script when installed as a dependency:

package.json


    {
      "bin": {
        "myapp": "bin/start.js"
      }
    }

When your package has been installed with npm install myapp, then node_modules/.bin/myapp will link to node_modules/myapp/bin/start.js and the user will be able to run it with npx myapp.

Upvotes: 1

Related Questions