使用webpack-dev-server设置Django

时间:2019-11-28 17:25:22

标签: javascript django webpack webpack-dev-server

使用Django设置webpack-dev-server无效。 我看了很多stackoverflow问题并阅读了tut,但似乎找不到我做错了什么。

这是我得到的错误:

  1. webpack编译失败,一吨
ERROR in ./node_modules/[package_name]/index.js
Module not found: Error: Can't resolve '[tls or fs or net]' in '/Users/user_name/project_folder/sub_folder/node_modules/[package_name]'
  1. 即使webpack失败,浏览器加载http://localhost:8080时也会出现Cannot GET /错误

我正在使用webpack-dev-server : "^3.9.0"

这是我的webpack.config.js

var path = require("path");
var BundleTracker = require('webpack-bundle-tracker');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var TerserPlugin = require('terser-webpack-plugin');
var webpack = require('webpack')


var rules = mode => {
    return [
        {
            test: /\.(ttf|eot|svg|woff|woff2|svg)?(\?[a-z0-9#=&.]+)?$/,
            loader: 'file-loader',
        },
        {
            test: /\.(js|jsx|mjs)$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options:
            {
                presets: [
                    ['@babel/preset-env', { corejs: 3, useBuiltIns: 'usage' }],
                    ['@babel/preset-react'],
                ],
                plugins: [
                    ["babel-plugin-styled-components"],
                    ["@babel/plugin-proposal-decorators", { legacy: true }],
                    ["@babel/plugin-proposal-class-properties", { "loose": true }],
                    "react-hot-loader/babel"
                ],
                cacheDirectory: true
            }
        }, // to transform JSX into JS
        {
            test: /\.(sa|sc|c)ss$/,
            use: [{
                loader: MiniCssExtractPlugin.loader,
                options: {
                    hmr: mode === 'development' ? true : false,
                },
            },
            { loader: 'css-loader', options: { importLoaders: 1 } },
                'postcss-loader',
                'resolve-url-loader',
                'sass-loader',
            ],
        }
    ];
}


module.exports = (env, argv) => {

    const mode = argv.mode;

    return [
        {
            entry: {
                'dashboard': './dashboard/assets/ui/app/index.jsx',
                'intake-form': './minisite/assets/base/intake-form',
            },
            output: {
                path: path.resolve(
                    mode === 'production'
                        ? './dashboard/static/bundles-production/'
                        : './dashboard/static/bundles-dev/'
                ),
                filename: "[name]-[hash].js",
            },
            module: { rules: rules(mode) },
            resolve: {
                modules: ['node_modules', 'bower_components'],
                extensions: ['.js', '.jsx'],
                alias: {
                   cs: path.resolve(__dirname, 'dashboard/assets'),
                }
            },
            optimization: {
                splitChunks: {
                    cacheGroups: {
                        vendor: {
                            chunks: "initial",
                            test: path.resolve(__dirname, "node_modules"),
                            name: "dashboard-vendor",
                            enforce: true
                        }
                    }
                },
                minimizer: [new TerserPlugin()],
                nodeEnv: mode,
            },
            plugins: [
                mode == 'development'
                    ? new CleanWebpackPlugin({
                        cleanOnceBeforeBuildPatterns: [
                            mode === 'production'
                                ? './dashboard/static/bundles-production/'
                                : './dashboard/static/bundles-dev/'
                        ]
                    })
                    : f => f,

                mode === 'production'
                    ? new BundleTracker({ filename: './webpack-stats-dashboard.production.json' })
                    : new BundleTracker({ filename: './webpack-stats-dashboard.json' }),

                new MiniCssExtractPlugin({ filename: '[name]-[contentHash].css' }),
                new webpack.HotModuleReplacementPlugin(),
            ],
            devServer: {
                contentBase: path.join(__dirname, "./"),
                historyApiFallback: true,
                //port: 9000,
                inline: true,
                hot: true,
                stats: 'errors-only',
                open: true,
            },
            devtool: mode === 'development' ? 'inline-source-map' : undefined,

        }
    ]
};

settings.py中的webpack配置如下


INSTALLED_APPS = (

    ...

    'webpack_loader',

)


################################################################
#
#       WEBPACK
#
################################################################

WEBPACK_DASHBOARD_BUNDLE_DIR_NAME = '/static/bundles-production/' if WEBPACK_USE_PRODUCTION_BUNDLES else \
                                    '/static/bundles-dev/'
WEBPACK_DASHBOARD_STATS_FILES = 'webpack-stats-dashboard.production.json' if WEBPACK_USE_PRODUCTION_BUNDLES else \
                                    'webpack-stats-dashboard.json'
WEBPACK_MINISITE_BUNDLE_DIR_NAME = '/static/bundles-production/' if WEBPACK_USE_PRODUCTION_BUNDLES else \
                                    '/static/bundles-dev/'
WEBPACK_MINISITE_STATS_FILES = 'webpack-stats-minisite.production.json' if WEBPACK_USE_PRODUCTION_BUNDLES else \
                                    'webpack-stats-minisite.json'


WEBPACK_LOADER = {
    'DASHBOARD'    : {
        'BUNDLE_DIR_NAME': WEBPACK_DASHBOARD_BUNDLE_DIR_NAME,
        'STATS_FILE': os.path.join(BASE_DIR, WEBPACK_DASHBOARD_STATS_FILES),
    },
    'MINISITE'    : {
        'BUNDLE_DIR_NAME': WEBPACK_MINISITE_BUNDLE_DIR_NAME,
        'STATS_FILE': os.path.join(BASE_DIR, WEBPACK_MINISITE_STATS_FILES),
    }
}

这是我的index.html文件

{% load custom_tags %}
{% load get_files from webpack_loader %}
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html style='min-height:100%;'>

    <head>
        <meta charset="UTF-8">
        <title>Website Name</title>
    </head>


    <body>
        <div id="app"></div>

        {% render_bundle 'dashboard-vendor' 'js' 'DASHBOARD' %}
        {% render_bundle 'dashboard' 'js' 'DASHBOARD' %}
    </body>
</html>

我正在使用的命令行是

webpack-dev-server --mode=development webpack.config.js

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

TerserPlugin您是否尝试过删除此插件,如果仍然出现此错误

。这件事在我身上也发生了