代码之家  ›  专栏  ›  技术社区  ›  pavlee

错误:“未捕获语法错误:意外标记<'(Django+React+Webpack)

  •  0
  • pavlee  · 技术社区  · 7 年前

    我在跟踪 this tutorial 设置Django以使用webpack生成的捆绑包提供模板。我已经像教程中一样设置了它。但问题是我什么时候去 localhost:8000 我明白了 Uncaught SyntaxError: Unexpected token < 在chrome devtools中打开控制台时出现异常。除了reactjs包之外,我放在模板文件中的其他html都会呈现出来。我的文件夹结构如下:

    .
    ├── djangoapp
    │   ├── db.sqlite3
    │   ├── djangoapp
    │   │   ├── __init__.py
    │   │   ├── settings.py
    │   │   ├── urls.py
    │   │   └── wsgi.py
    │   ├── manage.py
    │   ├── reactapp
    │   │   └── static
    │   │       ├── bundles
    │   │       │   └── main-fdf4c969af981093661f.js
    │   │       └── js
    │   │           └── index.jsx
    │   ├── requirements.txt
    │   ├── templates
    │   │   └── index.html
    │   └── webpack-stats.json
    ├── package.json
    ├── package-lock.json
    └── webpack.config.js
    

    设置。py公司

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'webpack_loader'
    ]
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, "templates"), ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WEBPACK_LOADER = {
        'DEFAULT': {
            'BUNDLE_DIR_NAME': 'bundles/',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
    }
    
    STATIC_URL = 'static/'
    

    网页包。配置。js公司

    var path = require("path");
    var webpack = require('webpack');
    var BundleTracker = require('webpack-bundle-tracker');
    
    module.exports = {
      context: __dirname,
    
      entry: './djangoapp/reactapp/static/js/index.jsx', 
    
      output: {
          path: path.resolve('./djangoapp/reactapp/static/bundles/'),
          filename: "[name]-[hash].js",
      },
    
      plugins: [
        new BundleTracker({filename: './djangoapp/webpack-stats.json'}),
      ],
    
      module: {
        rules: [
          { test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/},
          { test: /\.jsx$/, use: ['babel-loader'], exclude: /node_modules/}
        ]
      },
    
      resolve: {
        modules: ['node_modules', 'bower_components'],
        extensions: ['.js', '.jsx']
      },
    
    
    };
    

    模板/索引。html

    {% load render_bundle from webpack_loader %}
    <!DOCTYPE html>
    <html>
     <head>
     <meta charset="UTF-8">
     <title>Example</title>
     </head>
     <body>
     <div id="react"></div>
     {% render_bundle 'main' %}
     </body>
    </html>
    

    。巴别塔LRC

    {
      "presets": ["babel-preset-env", "react"]
    }
    

    异常在 main-fdf4c969af981093661f.js 文件,位于的开始标记上 <!DOCTYPE html> 要素我的猜测是,浏览器需要javascript代码,但它需要html。此外,我不明白Django如何知道在哪里查找捆绑包,因为我没有指定根( reactapp 目录)的 static/bundles 在任何地方

    2 回复  |  直到 7 年前
        1
  •  1
  •   pavlee    7 年前

    我在一段时间后通过将以下代码添加到 settings.py

    STATICFILES_DIRS = [
       ('bundles', os.path.join(BASE_DIR, 'reactapp/bundles'))
    ]
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    

    我也不得不改变 STATIC_URL /static/

    这就是它的工作原理:

    • Webpack生成绑定到 reactapp/bundles 文件夹
    • Django服务器运行时,会扫描内部的更改 反应应用程序/捆绑包 和 每次新更改后,将文件夹的内容复制到根目录 djangoapp/static/ 定义的文件夹 STATIC_ROOT 背景
    • 之后里面的文件 静态\u根 可通过浏览器访问 静态\u URL 像这样: localhost:8000/static/bundles/<bundle> 。通常默认为 localhost:8000/static/<bundle> 但是元组中的第一个元素 STATICFILES_DIRS 显式地告诉Django复制其中的内容 static/bundles 目录
    • Django然后在服务页面时自动生成指向静态文件的链接。

    注: 静态\u URL 应在前面加上 / 否则,静态路径将附加到当前页面链接,而不是根链接。E、 g上的 /index 页面指向静态文件的链接将是 localhost:8000/index/static/... 而不是 localhost:8000/static ,这将是错误的,并将导致 404 not found

        2
  •  0
  •   Anadi Sharma    7 年前

    这是一个棘手的问题!一切似乎都很顺利。首先,请确保 django-webpack-loader 按预期安装。其次,您的担心似乎是正确的,我们必须告诉django在默认情况下在哪里查找捆绑包 STATIC_URL + bundle_name (如以下文件所示: http://owaislone.org/blog/webpack-plus-reactjs-and-django/ )。尝试添加 publicPath webpack.config.js 作为:

    output: {
      path: path.resolve('./djangoapp/reactapp/static/bundles/'),
      filename: "[name]-[hash].js",
      publicPath: "http://localhost:8080/<path to bundles>"
    },
    

    我不确定它是否有效,但请让我知道它是否有用!