web-dev-qa-db-fra.com

Comment importer ou requérir un module ts dans un fichier commonJs

Pour certaines raisons, certains de mes modules doivent être des fichiers js.

Je import ts module dans mon fichier js comme ceci:

resolver.js:

import { Message } from '../../connectors/message';

// console.log('Message: ', Message);

const resolver = {
  Query: {
    sendMessage: (root, args, ctx) => {
      console.log(args, ctx);
      return Message.send('1', 'message');
    }
  }
};

export { resolver };

message.ts

const Message = {
  send(id, type) {
    return Promise.resolve({
      recipient_id: '123',
      message_id: '122'
    });
  }
};

export { Message };

J'utilise webpack to et awesome-TypeScript-loader pour compiler mes fichiers .ts.

voici mon tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es6", "esnext"],
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declaration": false,
    "outDir": "dist",
    "typeRoots": ["node_modules/@types"]
  },
  "files": ["src/main.ts"],
  "exclude": ["node_modules"]
}

webpack.config.js

var nodeExternals = require('webpack-node-externals');
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

/* helper function to get into build directory */
var distPath = function(name) {
  if (undefined === name) {
    return path.join('dist');
  }

  return path.join('dist', name);
};

var webpack_opts = {
  entry: './src/main.ts',
  target: 'node',
  output: {
    filename: distPath('main.js'),
    libraryTarget: 'commonjs2'
  },
  resolve: {
    extensions: ['.ts', '.js'],
    modules: ['node_modules', 'src']
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        test: /\.ts$/,
        ts: {
          compiler: 'TypeScript',
          configFileName: 'tsconfig.json'
        },
        tslint: {
          emitErrors: true,
          failOnHint: true
        }
      }
    })
  ],
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: 'awesome-TypeScript-loader'
      }
    ]
  },
  externals: [nodeExternals()]
};

module.exports = webpack_opts;

Mais j'ai eu cette erreur: 

(function (exports, require, module, __filename, __dirname) { import { Message } from '../../connectors/message';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (internal/modules/cjs/loader.js:618:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)

Comment résoudre ceci? Merci.

- mise à jour v1 - 

J'essaie de l'utiliser avec require

// import { Message } from '../../connectors/message';

const { Message } = require('../../connectors/message');

console.log('Message: ', Message);

const resolver = {
  Query: {
    sendMessage: (root, args, ctx) => {
      console.log(args, ctx);
      return Message.send('1', 'message');
    }
  }
};

export { resolver };

Mais j'ai toujours une erreur: 

internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module '../../connectors/message'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at Object.<anonymous> (/Users/ldu020/workspace/workplace-adapter-graphql/src/graphql/modules/messages/resolver.js:3:21)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)

- mise à jour v2 - 

J'ajoute l'extension de fichier .ts au chemin: 

const { Message } = require('../../connectors/message.ts');

toujours eu l'erreur: 

    export { Message };
^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (internal/modules/cjs/loader.js:618:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)

mise à jour 3 : ajouter package.json

"devDependencies": {
    "@types/faker": "^4.1.4",
    "@types/jest": "^19.2.4",
    "@types/node": "^7.10.0",
    "babel-cli": "^6.26.0",
    "faker": "^4.1.0",
    "jest": "^20.0.4",
    "ts-jest": "^20.0.6",
    "ts-node": "^3.2.0",
    "tslint": "^5.11.0",
    "TypeScript": "^2.9.2"
  },
5
slideshowp2

essayez d'utiliser require('../../connectors/message')

1
Rahul Bisht

la version de votre nœud ne prend pas en charge import. use require à la place:

var Message = require('./path').Message;

- update - puisque vous essayez d'importer un fichier .ts, vous devez l'écrire dans le chemin. comme ceci: require('./path.ts');

0
Amirali Ameri