Django/Webpack-如何使用Webpack开发服务器提供生成的Webpack捆绑包 [英] Django/Webpack - How to serve generated webpack bundles with webpack dev server

查看:66
本文介绍了Django/Webpack-如何使用Webpack开发服务器提供生成的Webpack捆绑包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的"static"标记使用STATIC_URL生成网址,其结果类似于"/static/myapp/js/bundle.js"同时,webpack-dev-server正在从url'localhost:3000'提供捆绑服务

Django's 'static' tag generates urls using STATIC_URL, which results in something like '/static/myapp/js/bundle.js' Mean while, webpack-dev-server is serving bundles from the url 'localhost:3000'

我的问题是我如何获取Django静态"模板标签以为js捆绑包生成一个不同的url(指向webpack开发服务器).当然,我可以在模板中对其进行硬编码,但这不是一个好的解决方案.

My question is how do I get Django 'static' template tag to generate a different url ( which points to webpack dev server) for js bundles. Of course I can hardcode it in the template, but that would not be a good solution.

下面是我的项目配置

webpack.config.js

webpack.config.js

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const BundleTracker = require('webpack-bundle-tracker')


module.exports = {
    mode: 'development',
    context: path.dirname(path.resolve(__dirname)),
    entry: {
        index: './typescript_src/index.ts',
    },
    output: {
        path: path.resolve('./myproject/assets/myapp/bundles/'),
        filename: "[name]-[hash].js"
    },
    resolve: {
        extensions: ['.ts', '.js' ]
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.ts$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new BundleTracker({filename: './myproject/webpack-stats.json'})
    ],
    devServer: {
        port: 3000,
        publicPath: '/myapp/bundles/',
        // hot: true,
        headers: {
            "Access-Control-Allow-Origin": "http://127.0.0.1:8000", /**Django dev server */
        }
    }
}

settings.py

settings.py

WEBPACK_LOADER = {
    'DEFAULT': {
        'CACHE': not DEBUG,
        'BUNDLE_DIR_NAME': 'myapp/bundles/', # must end with slash
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        'POLL_INTERVAL': 0.1,
        'TIMEOUT': None,
        'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
    }
}

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

最初,我决定webpack在开发过程中也应提供其他静态文件

Initially I decided webpack should serve other static files as well during development

webpack.config.js

webpack.config.js

devServer: {
        port: 3000,
        publicPath: '/myapp/bundles/',
        contentBase: path.resolve('./myproject/assets')
        // hot: true,
        headers: {
            "Access-Control-Allow-Origin": "http://127.0.0.1:8000", /**Django dev server */
        }

settings.py

settings.py

# in development mode serve from wepack dev server
if DEBUG:
    STATIC_URL = 'http://localhost:3000/'
else:
    STATIC_URL = '/static/'

但是后来我意识到我必须提供其他应用程序的静态文件(管理员,tinymce等),这对于webpack开发服务器来说是不可能的

But I later realized I have to serve static files of other apps (admin, tinymce, ...), which is impossible for webpack Dev server to reach

这里的问题是django-webpack-loader(/static/myapp/bundles/bundle-name.js)的'render_bundle'标签生成的网址将导致Http 404,因为webpack-dev-server会保留生成的捆绑包在内存中而不在磁盘上

The problem here is that the url generated by 'render_bundle' tag of django-webpack-loader (/static/myapp/bundles/bundle-name.js) will result in a Http 404 because webpack-dev-server keeps the generated bundle in memory and not on disk

如果我也设置

STATIC_URL = localhost:3000

并配置webpack-dev-server来提供我的应用程序的其他静态文件,但不会提供其他应用程序的静态文件

and configure webpack-dev-server to serve other static files of my app, static files of other apps won't be served

推荐答案

让我们分析问题:

我们有2台服务器,我们希望根据请求的路径将请求路由到一个或另一个:

We have 2 servers and we want to route requests to one or the other based on the path requested:

"/static/webpackbundles/** ==> webpack开发服务器

其他路径==>django开发服务器

这恰好是代理服务器的工作,可以通过第三台服务器(haproxy,nginx ...)来实现,但这似乎是一个过大的选择,尤其是如果我们知道 webpack dev server 可以用作代理!( https://webpack.js.org/configuration/dev-server/#devserverproxy )

This is exactly the job of a proxy server, it can be achieved with a third server (haproxy, nginx ...), but that might seem like an overkill, especially if we know that webpack dev server can be used as a proxy! (https://webpack.js.org/configuration/dev-server/#devserverproxy)

webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: '/path/to/django_project/django_project/static/webpackbundles',
    publicPath: '/static/webpackbundles/',
  },
  devServer: {
    contentBase: '/path/to/django_project/django_project/static/webpackbundles',
    hot: true,
    proxy: {
      '!/static/webpackbundles/**': {
        target: 'http://localhost:8000', // points to django dev server
        changeOrigin: true,
      },
    },
  },
};

在您的Django模板中:

In your django template:

<script type="text/javascript" src="{% static 'webpackbundles/main.js' %}"></script>

现在使用 webpack开发服务器地址访问您的Django应用/站点:例如: http://localhost:8081

Now access your django app/site using webpack dev server address: ex: http://localhost:8081

通过此简单的配置,您将拥有浏览器自动刷新和热模块更换的功能.您将不需要在django中进行任何更改,也不需要django-webpack-loader

With this simple config you'll have browser auto refresh and hot module replacement. You will not need to change anything in django, also no need for django-webpack-loader

这篇关于Django/Webpack-如何使用Webpack开发服务器提供生成的Webpack捆绑包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆