11

I have tried to find an answer to this solution but the answers I have found are usually to do with adding 'module' to a script tag (which doesnt apply in my case since I'm not writing browser code) or using import/export in a javascript file (which is not currently supported by Node) which means the need to use babel or typescript. Since I am seeing this error in a typescript project, I don't expect to see this error.

Actually, I have 2 typescript/webpack projects (with near identical setup, project A depends on project B) 1 importing definitions from the other.

In project B, I have several classes, 2 of which are exported, plus some other definitions. In project B's index.ts:

export * from './types';
export * from './specService/spec-option-service.class';
export * from './converter/xpath-converter.class';

and those are exported like so:

// types.ts
//
export interface IElementInfo {
  readonly id?: string;
  readonly recurse?: string;
  readonly discards?: ReadonlyArray<string>;
  readonly descendants?: {
    readonly by?: string;
    readonly throwIfCollision?: boolean;
    readonly throwIfMissing?: boolean;
  };
}

// ... plus other similarly defined exports
// specService/spec-option-service.class.ts
//
export class SpecOptionService { ...
// converter/xpath-converter.class.ts
//
export class XpathConverter { ...

And then in project B's index.ts, I export all the definitions (export * from blah) for use by the client as shown at the top of this post.

When I build project B, there is no such issues with the export.

After installing project B into project A

from a typescript file I am importing using:

import * as ProjectB from 'projectb';

Webpack successfully even builds project A's bundle, with no error. The error occurs at runtime, in this case when I go to run the tests at which point I see the following:

/Users/User/dev/github/js/projecta/node_modules/projectb/lib/index.ts:2
export * from './types';
^^^^^^

SyntaxError: Unexpected token 'export'
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.projectb (/Users/User/dev/github/js/projecta/dist/projecta-test-bundle.js:292:18)

At the end of projectb's webpack bundle, I found the following:

module.exports = webpack_require(/*! ./lib */"./lib/index.ts");

which I believe is at fault. Why does the bundle built by webpack for an "es5" target contain references to typescript? Isn't this bound to fail? I would have expected a require on the generated index.js file (not index.ts).

This is the first time I've done import/export across project boundaries in typescript so I know that I doing something wrong but what?

The tsconfig.json file in both projects are the same:

{
  "compilerOptions": {
    "allowJs": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "Node",
    "noImplicitAny": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "types": [
      "mocha", "node"
    ],
    "lib": [
      "es5",
      "es2015",
      "es6",
      "dom"
    ]
  },
  "include": [
    "lib/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

And the webpack config:

{
    devtool: 'source-map',
    entry: {
      index: './lib/index.ts'
    },
    target: 'node',
    mode: mode,
    externals: [nodeExternals()],
    module: {
      rules: [
        {
          test: /\.ts(x?)$/,
          use: 'ts-loader'
        },
        {
          test: /\.json$/,
          use: 'json-loader'
        }
      ]
    },
    plugins: [
      new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }),
      new webpack.BannerPlugin({
        banner: '#!/usr/bin/env node',
        raw: true
      })
    ],
    resolve: {
      extensions: ['.ts', '.js', '.json']
    },
    watchOptions: {
      ignored: /node_modules/
    },
    output: {
      filename: 'projecta-bundle.js',
      sourceMapFilename: 'projecta-bundle.js.map',
      path: path.join(__dirname, 'dist'),
      libraryTarget: 'commonjs'
    }
  }

Project A and B are plastikfan/jaxom and plastikfan/zenobia respectively. Before publishing the latest version of jaxom to npm, I am performing pre-npm-publish check (learnt that this is a wise thing to do with early npm packages) to check that clients can use the package as expected. (I've had problems in tha past where I've made a mistake in exporting something, but this does not become apparent until a client tries to use it. It's not somthing you can check for as far as I know before you publish. The advised way to to do this is to pack up your package using nom pack then install it into the client).

fyi, zenobia package.json is (cutdown version):

{
  "name": "zenobia",
  "version": "0.0.1",
  "main": "lib/index.ts",
  "scripts": {
    "t": "mocha ./dist/zenobia-test-bundle.js",
    "test": "npm audit --skip-unused && npm run t",
    "build": "npm run build:d",
    "build:d": "webpack -d --env.mode development",
    "build:p": "webpack -p --env.mode production",
    "build:t": "webpack --config webpack.config.test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/plastikfan/zenobia.git"
  },
  "dependencies": {
    "@types/node": "^12.12.14",
    "@types/ramda": "^0.26.36",
    "jaxine": "^2.0.1",
    "jaxom": "file:../NPM-LOCAL/jaxom-0.0.1.tgz",
    "ramda": "^0.26.1",
    "xmldom": "^0.1.27",
    "xpath": "0.0.27"
  },
  "devDependencies": {
    "@commitlint/cli": "^8.3.3",
    "@commitlint/config-conventional": "^8.2.0",
    "@types/chai": "^4.2.5",
    "@types/dirty-chai": "^2.0.2",
    "@types/mocha": "^5.2.7",
    "@types/sinon": "^7.5.1",
    "@types/sinon-chai": "^3.2.3",
    "chai": "^4.2.0",
    "commitizen": "^4.0.3",
    "cz-conventional-changelog": "^3.0.2",
    "depcheck": "^0.9.1",
    "dirty-chai": "^2.0.1",
    "mocha": "^6.2.2",
    "nyc": "^14.1.1",
    "precommit-hook": "^3.0.0",
    "raw-loader": "^4.0.0",
    "rimraf": "^3.0.0",
    "semistandard": "^14.2.0",
    "shebang-loader": "0.0.1",
    "sinon": "^7.5.0",
    "snazzy": "^8.0.0",
    "ts-loader": "^6.2.1",
    "tslint": "^5.20.1",
    "tslint-config-semistandard": "^8.0.1",
    "typescript": "^3.7.2",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-config-utils": "^2.3.1",
    "webpack-node-externals": "^1.7.2"
  }
}

And jaxom's cutdown package.json:

{
  "name": "jaxom",
  "main": "./lib/index.ts",
  "scripts": {
    "clean": "rimraf dist && rimraf decl",
    "t": "mocha ./dist/jaxom-test-bundle.js",
    "test": "npm audit --skip-unused && npm run t",
    "build": "npm run build:d",
    "build:d": "webpack -d --env.mode development",
    "build:p": "webpack -p --env.mode production",
    "build:t": "webpack --config webpack.config.test.js"
  },
  "dependencies": {
    "@types/ramda": "^0.26.36",
    "@types/xregexp": "^3.0.30",
    "jinxed": "0.0.2",
    "moment": "^2.24.0",
    "ramda": "^0.26.1",
    "xmldom-ts": "^0.3.1",
    "xpath-ts": "^1.3.13",
    "xregexp": "^4.2.4"
  },
  "devDependencies": {
    "@commitlint/cli": "^8.2.0",
    "@commitlint/config-conventional": "^8.2.0",
    "@types/chai": "^4.2.5",
    "@types/dirty-chai": "^2.0.2",
    "@types/mocha": "^5.2.7",
    "@types/sinon": "^7.5.1",
    "@types/sinon-chai": "^3.2.3",
    "chai": "^4.2.0",
    "commitizen": "^4.0.3",
    "cz-conventional-changelog": "^3.0.2",
    "depcheck": "^0.9.1",
    "dirty-chai": "^2.0.1",
    "json-loader": "^0.5.7",
    "mocha": "^6.2.2",
    "precommit-hook": "^3.0.0",
    "raw-loader": "^4.0.0",
    "rimraf": "^3.0.0",
    "sinon": "^7.5.0",
    "sinon-chai": "^3.3.0",
    "snazzy": "^8.0.0",
    "ts-loader": "^6.2.1",
    "tslint": "^5.20.1",
    "tslint-config-semistandard": "^8.0.1",
    "typescript": "^3.7.2",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-config-utils": "^2.3.1",
    "webpack-node-externals": "^1.7.2"
  }
}

3 Answers 3

11

For me, it was the module key in tsconfig.json.

I changed it from this: "module": "esnext" to this: "module": "commonjs"

3

I think tsconfig can be a problem here.
Because when you are importing import * as ProjectB from 'projectb'; your projectB files will not be transpiled by typescript because of include and exclude properties of projectA tsconfig. Try add projectB to the compilation process of projectA.
Something like include: [ "lib/**/*", "my/path/to/projectB/**"] in projectA tsconfig.

7
  • Thanks Nick. So when you say "my/path/to/projectB/**", what does that mean? Project B is a different npm package, so I don't really know what path to project B means. Aren't dependencies defined in package.json? I'm using other typescript projects without them being in "include", so what have I done wrong to need that?
    – Plastikfan
    Commented Dec 4, 2019 at 9:47
  • @Plastikfan other typescript packages already transpiled to js for you by it's creators (check it in node_modules folder). There are two ways to get it working 1) transpile projectB before running projectA (in projectB run npm run build or another command you created for building it). Then in projectA you need to import dist of projectB (not src!) where javascript code is. 2) transpile projectB together with projectA. To do it you need to add it to tsconfig include. Path should be like include: ["node_modules/projectB"] Commented Dec 4, 2019 at 9:58
  • @Plastikfan what i'm trying to say - no one publish untranspiled typescript code to the npm. All the packages usually contains js code with .d.ts typings Commented Dec 4, 2019 at 9:59
  • Ok thanks Nick. I think you may have mis-understood me slightly. Project A is not directly accessing project B's typescript. B is just like any other typescript project that has been transpiled to js.
    – Plastikfan
    Commented Dec 4, 2019 at 10:20
  • @Plastikfan Ok, then it is very strange. Can you please show me package.json of projectB? Or property main at least. Main file should be something like ` "main": "dist/bundles/projectb.umd.js",` Commented Dec 4, 2019 at 10:59
-3

Try adding "type":"module" to the package.json.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.