如何导入或要求ts模块到commonJs文件中

时间:2018-04-16 07:19:03

标签: javascript typescript webpack ecmascript-6

由于某种原因,我的一些模块必须是js个文件。

import ts模块进入我的js文件,如下所示:

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 };

我使用webpackawesome-typescript-loader来编译我的.ts文件。

这是我的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;

但我收到了这个错误:

(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)

如何解决这个问题?感谢。

- 更新v1 -

我尝试将其与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 };

但我仍然有错误:

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)

- 更新v2 -

我将.ts文件扩展名添加到路径:

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

仍有错误:

    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)

更新3 :添加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"
  },

2 个答案:

答案 0 :(得分:1)

尝试使用require('../../connectors/message')

答案 1 :(得分:0)

您的节点版本不支持import。改为使用require:

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

- 更新 - 因为您尝试导入.ts文件,所以需要在路径中写入该文件。像这样:require('./path.ts');