【问题标题】:Using an ES6 module in both an app and in Node, while using Webpack-Dev-Middleware and Express在应用程序和 Node 中使用 ES6 模块,同时使用 Webpack-Dev-Middleware 和 Express
【发布时间】:2018-10-20 00:54:04
【问题描述】:

背景

假设你有一个 ES2015/ES6 组件,它有一个函数作为默认导出:

component.js

export default function() {
    console.log("Hello, World!");
}

将其包含在其中的应用:

app.js

import myComponent from "./component"

myComponent();

还有一个使用 webpack-dev-middleware 的 Node.js/Express 服务器,用于在 app.js 上运行 Webpack(带有 Babel)并提供服务,并且component.js 包含在:

server.js

const express = require("express");
const app = express();

// start the server
app.listen(process.env.EXPRESS_PORT, () => {
    console.log(`App listening on port ${process.env.EXPRESS_PORT}!`);
});

const webpack = require("webpack");
const webpackConfig = require("./webpack.config");
const compiler = webpack(webpackConfig);

// use webpack-dev-middleware to serve the publicPath
app.use(
    require("webpack-dev-middleware")(compiler, {
        logLevel: "warn",
        publicPath: webpackConfig.output.publicPath,
    })
);

// use webpack-hot-middleware for HMR
app.use(require("webpack-hot-middleware")(compiler));

const myComponent = require("./component") // import the component
myComponent(); // use the component

问题

您如何在server.js 和webpacked app.js 中使用component.js

问题

按原样,该组件在app.js 中运行良好,但在尝试执行const component = require("./component") 时会在节点控制台中抛出SyntaxError: Unexpected token export

由于 Babel 仅通过 Webpack 运行,而 server.js 是通过原始组件而不是捆绑/转译的组件访问 component.js,因此我们得到了错误。

我想一个解决方案是运行 Babel 两次:在启动 server.js 之前在组件上运行一次,然后在 Webpack 中运行一次,但这似乎非常不优雅和低效。

【问题讨论】:

  • 听起来也许您应该创建第三个使用您的组件编译的库,然后将编译后的库导入您的服务器端和客户端代码。
  • 要在节点上使用 ES6 模块,您需要使用 --experimental-modules 标志并将文件命名为 .mjs,请参阅:nodejs.org/api/esm.html
  • @GabrielCarneiro,对不起,我应该更清楚;我宁愿避免使用实验性功能,除非它们是合法的最佳选择。这个问题似乎不需要求助就可以解决。我也不一定想将 ES6 模块导入 Node;我想将它作为 CommonJS 转换并导入到 Node 中,同时不理会它,以便可以将它作为 ES6 模块导入到其他地方。

标签: javascript node.js webpack babeljs webpack-dev-middleware


【解决方案1】:

我似乎偶然发现了一个可行的解决方案:以 CommonJS 格式编写模块,Webpack/Babel 将为 ES6 编译它。

工作文件:

component.js

function myComponent() {
    console.log("Hello, World!");
}

module.exports = { myComponent };

app.js

import myComponent from "./component"

myComponent();

server.js

const { myComponent } = require("./component") // import the component

myComponent(); // use the component

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2015-08-16
    • 2018-11-26
    • 2019-07-21
    • 2017-11-09
    • 2021-04-07
    • 2020-07-09
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多