我遵循this tutorial来设置Django以使用webpack生成的包提供模板。我已经按照教程中的说明进行了设置。但是问题是当我转到localhost:8000时,在chrome devtools中打开控制台时出现Uncaught SyntaxError: Unexpected token <异常。我放到模板文件中的其他html会被渲染,除了reactjs包。我的文件夹结构如下:

.
├── 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


settings.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/'


webpack.config.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']
  },


};


templates / index.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>


.babelrc

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


main-fdf4c969af981093661f.js文件的第一行的<!DOCTYPE html>元素的开始标记处引发异常。我的猜测是浏览器需要javascript代码,但它却是html。另外,由于我没有在任何地方指定reactapp的根目录(static/bundles目录),所以我不理解Django如何知道在哪里寻找捆绑软件。

最佳答案

过一会儿,我通过将以下代码添加到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服务器运行时,它会扫描reactapp/bundles
每次新更改后,都将文件夹的内容复制到djangoapp/static/设置所定义的根STATIC_ROOT文件夹中。
之后,浏览器可以通过STATIC_ROOT通过STATIC_URL访问localhost:8000/static/bundles/<bundle>中的文件:localhost:8000/static/<bundle>。它通常默认为STATICFILES_DIRS,但是static/bundles中元组的第一个元素明确告诉Django复制STATIC_URL目录中的内容。
然后,Django在提供页面时会自动生成指向静态文件的链接。


注意:/应该以/index开头,否则静态路径将附加到当前页面链接而不是根目录。例如,在localhost:8000/index/static/...页面上,指向静态文件的链接将是localhost:8000/static而不是404 not found,这将是错误的并导致。

关于javascript - 错误:“未捕获的语法错误:意外的 token <”(Django + React + Webpack),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49128992/

10-12 12:54
查看更多