Search code examples
node.jsmoduleazure-functionschalk

Why isn't my Node package being imported?


I'm learning Node.js and am using a Node-based Azure Function.

I'm trying to bring in Chalk, to log coloured messages to the console.

However, all of the below fail (in my main index.js file).

One

module.exports = async (ctx, req) => {
    const chalk = require('chalk');
    return console.log(chalk.blue('Hello world!'));

Despite being the approach recommended in this answer, this results in a console error that says:

Exception: require() of ES Module C:...\node_modules\chalk\source\index.js from C:...\index.js not supported. Instead change the require of C:...\chalk\source\index.js in C:...\index.js to a dynamic import() which is available in all CommonJS modules.

Two

If I do as the error suggests, and use

const chalk = async import('chalk')

...I then get

Exception: chalk.blue is not a function

...even though console.log(chalk) does seem to show the Chalk API and its various properties.

Three

The Chalk docs themselves recommend this:

module.exports = async (ctx, req) => {
    import chalk from 'chalk'
    return console.log(chalk.blue('Hello world!'));

That yields an error saying I can't use import outside of a module (but surely I'm in one?)

Four

Same as three ^^ but moving the import outside module.exports:

import chalk from 'chalk'
module.exports = async (ctx, req) => {
    return console.log(chalk.blue('Hello world!'));

...yields the same error.

I'm sure this is a basic error but I can't find what I'm doing wrong so I'd be so grateful if someone could help. Thank you!


Solution

  • When you import something using import as a function(lazy import), It'll return an object with a default property and all exported properties. That you should use to access the module.

    const module = async import('chalk')
    const chalk = module.default
    console.log(chalk.red('Hello world!'))