节点-无法运行Webpack捆绑包

时间:2019-01-15 15:12:00

标签: javascript node.js webpack webpack-4

我正在使用webpack捆绑我的应用程序,并确保将目标指定为“节点”(否则webpack构建失败)。

使用我当前的配置,构建成功,但是当我尝试使用节点运行它时,出现错误:

  

C:\ Users \ myuser \ Desktop \ myproject \ dist \ app.js:20 / ****** /
  modules [moduleId] .call(module.exports,module,module.exports,    webpack_require );                                             ^

     

TypeError:无法读取未定义的属性“调用”

这是指webpackBootstrap函数内部插入到app.js开头的一行。感觉好像节点与Webpack不兼容,尽管据我所知应该如此。

我怀疑这与问题有关,但为了让您了解完整情况:

我正在编译ts,并将src中的每个文件作为单独的块导出到dist中,而不是将所有内容捆绑在一起,以便在运行时按需动态导入文件。

例如:

  • src / app.ts
  • src / compA.ts
  • src / compB.ts

将变为:

  • dist / app.js
  • dist / compA.js
  • dist / compB.js

这是我的webpack.config.js:

const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const { CheckerPlugin } = require('awesome-typescript-loader');
const glob = require('glob');

let entry = {};

glob.sync('./src/**/*.*').forEach(component => {
    let name = component.match(/.*\/(.*)\..*/)[1];

    entry[name] = component;
});

module.exports = {
    mode: 'development',
    entry,
    target: 'node',
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist'
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'awesome-typescript-loader'
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new CheckerPlugin()
    ],
    output: {
        filename: (chunkData) => {
            let name = chunkData.chunk.name;
            let src = chunkData.chunk.entryModule.id;

            let path = src.split('/');
            let dir = path[path.length -2];
            let pathPrefix = dir !== 'src' ? dir + '/' : '';

            return pathPrefix + name + '.js';
        },
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        },
    },
};

1 个答案:

答案 0 :(得分:0)

我需要在配置中包括节点外部。

const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
  target: "node",
  entry: {
    app: ["./back.js"]
  },
  output: {
    path: path.resolve(__dirname, "../build"),
    filename: "bundle-back.js"
  },
  externals: [nodeExternals()],
};

https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-end-b95f1b429810