如何在打字稿中使用带有es6导入语法的节点模块

问题描述 投票:1回答:2

我有一个打字稿项目,它使用我们的一个节点模块,通常在我们的前端运行。我们现在希望在我们的服务器上的节点中使用此模块。

该模块使用es6导入语法import { props } from 'module/file'

当我使用以下任一方法包含ref in typescript时

import { props } from 'module/file';
var props = require('module/file');

我从打字稿中得到以下错误

unexpected token 'import' 
(function (exports, require, module, __filename, __dirname) { import

重新编写模块是一项很大的工作,我尝试过使用babel-plugin-dynamic-import-node以及SystemJS。

这些系统的问题是它们都是异步的,所以我不能以标准方式导入模块,所以当我们到达可以使用本机导入的点时,我需要做一大堆重写。在node.js.中

我不能成为第一个遇到这个问题的人,但我似乎无法找到一个有效的解决方案。

---------------更新设置-------------

回应@ DanielKhoroshko的回应。我试图导入的原始模块通常由webpack打包,以便在前端使用。我现在尝试在服务器端和前端(通过前端的webpack)使用相同的模块,而无需重新编写imports以使用require并且无需运行webpack来捆绑要在服务器上使用的js 。

为了清楚起见,原始模块是用JS编写的,我们试图使用这个模块的服务是用typescript编写并编译的。当打字稿尝试require使用import的旧模块时,就在这时我们遇到了问题。

------------------一些进步---------------------------

我通过在我导入的模块中创建一个文件取得了一些进展,该模块使用node.js中的babel将es6代码转换为commonJS模块。

我通过这样做了

var babel = require("babel-core")

var store = babel.transformFileSync(__dirname + '/store.js', {
    plugins: ["transform-es2015-modules-commonjs"]
});

module.exports = {
    store: store.code
}

我现在可以在我的新node.js项目中获取store。但是,store.js文件中的子模块不包含在导出中。

所以在我的模块中,它说import activities from './reducers/activities';我现在得到一个错误Cannot find module './reducers/activities'

如何让babel进行深度遍历以包含子目录?

node.js typescript import es6-modules
2个回答
1
投票

unexpected token 'import'表示您在不支持import/export命令的环境中运行es-modules代码。如果您在TypeScript中编写代码,那么在构建浏览器之前首先将其转换为或者使用ts-node在服务器端运行它是很重要的。

如果您使用webpack,则有装载机ts-loaderawesome-typescript-loader

你的设置是什么?


要描述模块,您需要在同一文件夹中创建一个activities.d.ts文件,其中js-version(我理解它被称为activities.js和容器一个reducer)驻留在以下(约):

import { Reducer } from 'redux';

export const activities: Reducer<any>;

1
投票

@Daniel Khoroshko在很多方面是正确的,我最终找到@std/esm,它允许你导入es6模块,并找到了获取包含的导入。

var babel = require('babel-register')({
    presets: ["env"]
});

    require = require('@std/esm')(module);

    var store = require('ayvri-viewer/src/store');

    exports.default = {
        store: store
    }

我不得不运行babel来获得从es6到节点兼容的es5的一致构建

© www.soinside.com 2019 - 2024. All rights reserved.