Search code examples
node.jstypescriptecmascript-6commonjs

Why does syntax error occurs in a Typescript-written node_module?


node_modules/
  my_module/
    lib/
      index.ts
src/
  index.ts

I made a custom module my_module and wanted to use it as an external library. The codes are like below:

[src/index.ts]

import { hello } from 'my_module'
console.log(hello)

[node_modules/my_module/index.ts]

export const hello = "Hello"

My tsconfig.json says "module": "commonjs", "target": "es6", so I thought import keywords would work nicely in Typescript files.

As I expected, the import keyword in src/index.ts works well, but the export keyword in node_modules/my_module/index.ts is an unexpected token. How can I get this problem solved?

export const hello = "hello"
^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:685:28)
    at Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:431:14)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:658:17)

Solution

  • Unless the project was configured to transpile modules from node_modules (this is generally discouraged because this is inefficient and unneeded), it's expected that external module will be evaluated as is, and import keyword is not allowed in CommonJS modules.

    my_module should be compiled before publishing, i.e. tsc should be executed, and dist should contain transpiled *.js and *.d.ts typings.

    main in my_module package.json should specify entry point, "main": "dist/index.js".

    The package can optionally contain .npmrc file to exclude src from published files, but this is not necessary.