網站搜尋

node.js - 如何在 TypeScript 中使用 ES6 import 語法導入 Node 模組


我有一個 TypeScript 專案,它使用了我們的一個 Node 模組,這個模組通常在我們的前端運行。我們現在打算在伺服器的 Node 上使用這個模組。

該模組使用 es6 導入語法 import { props } from 'module/file'

當我在 TypeScript 中使用以下任一方法包含 ref 時

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

我從 TypeScript 得到以下錯誤

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

重寫這個模組是一個大工程,我已經嘗試過使用 babel 搭配 babel-plugin-dynamic-import-node,以及 SystemJS。

這些系統的問題在於它們都是非同步的,所以我無法以標準方式導入模組,因此當我們可以在 node.js 中原生使用 import 時,我將需要做大量的重寫。

我不可能是第一個遇到這個問題的人,但我似乎找不到有效的解決方案。

--------------- 使用設定更新 -------------

回應 @DanielKhoroshko 的回覆。我原本嘗試引入的模組通常由 webpack 打包以便在前端使用。我現在嘗試在伺服器端和前端(透過前端的 webpack)都使用這同一個模組,而不重寫 imports 來使用 require,也不在伺服器端執行 webpack 去打包 js。

為了說明清楚,原本的模組是用 JS 撰寫的,我們試圖使用該模組的服務則是用 TypeScript 撰寫並轉譯的。當 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 進行深度遍歷以包含子目錄?

答案#1

unexpected token 'import' 意味著你正在不支援 import/export 指令的環境中執行 es-modules 代碼。如果你是在使用 TypeScript 編寫代碼,重要的是在為瀏覽器構建之前先進行轉譯,或者使用 ts-node 在伺服器端運行它。

如果你正在使用 webpack,有加載器 ts-loader 和 awesome-typescript-loader

你的設備配置是什麼?

要描述這個模組,你需要在與 js 版本(我理解它叫做 activities.js 並包含一個 reducer)所在的同一個資料夾中,建立一個 activities.d.ts 檔案,內容大約如下:

import { Reducer } from 'redux';

export const activities: Reducer<any>;

答案#2

@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 生成與 Node 相容的 ES5 的一致構建