[英]Load javascript files outside Django project
Today, I'm trying to add web pack to my Django project.今天,我正在尝试将 web pack 添加到我的 Django 项目中。 I got webpack working fine.
我让 webpack 工作正常。
My goal is to load the new compiled javascript into my project's template/base.html.我的目标是将新编译的 javascript 加载到我项目的 template/base.html 中。
This is the static section for my setting.py file of my project.这是我的项目的 setting.py 文件的静态部分。
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
#'django.core.context_processors.csrf'
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': DEBUG,
},
},
]
This is my webpack configuration:这是我的 webpack 配置:
const path = require("path");
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
const config = {
context: __dirname,
entry: {
app: './webpack/assets/javascript/entry/app.js'
},
output: {
path: path.join(__dirname, 'public', 'assets'),
publicPath: '/assets/',
filename: "[name].js",
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
]
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
resolve: {
extensions: ['.js', '.json'],
modules: ['./webpack/assets/javascript/', './vendor/assets/javascript', 'node_modules']
}
};
module.exports = config;
As you can tell from my web pack.config, I'm creating an app.js file inside Public/assets on my root directory folder.从我的 web pack.config 中可以看出,我正在我的根目录文件夹的 Public/assets 中创建一个 app.js 文件。
How can I add my public/assets folder to my static files, so I can add the following script on my project's folder templates/base.html?如何将我的 public/assets 文件夹添加到我的静态文件中,以便我可以在我的项目文件夹 templates/base.html 中添加以下脚本?
<script src="app.js"></script>
This is the folder diagram:这是文件夹图:
The help will be appreciated.将不胜感激。
The static
template tag allows you to link to files saved in STATIC_ROOT
. static
模板标签允许您链接到保存在STATIC_ROOT
文件。
So if you have所以如果你有
STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'),)
and your app.js
file is saved in /path/to/my/project/static/public/assets/app.js
then the following should link to your file并且您的
app.js
文件保存在/path/to/my/project/static/public/assets/app.js
然后以下内容应链接到您的文件
{% load static %}
<script src="{% static "public/assets/app.js" %}"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.