angularjs - Wepback导入html模板未加载
问题描述
我有一个使用 Webpack 使用 AngularJS 制作的单体项目,但我收到一条错误消息:Unexpected token < main.html.
当我的一个控制器中有这行代码时会发生此错误:
import templateUrl from './main.html';
据我了解,在我看来,Webpack 没有正确捆绑我的 HTML 模板。该<
符号来自 main.html 模板,成功找到但未解析。然后我考虑以html-loader
这种方式使用和使用它:
import templateUrl from 'html-loader!./main.html';
令我惊讶的是,这并不能解决问题。
我正在使用 Webpack 版本"webpack": "^3.4.1",
,这是我的配置:
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ContextReplacementPlugin =
require('webpack/lib/ContextReplacementPlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = nodeEnv === 'production';
const styles = [
'css-loader?importLoaders=1',
'postcss-loader',
'sass-loader'
];
module.exports = {
entry: {
'root-application': 'src/root-application/root-application.js',
},
output: {
publicPath: '/dist/',
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.scss$/,
use: !isProd
? [
'style-loader',
...styles
]
: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: styles
}),
exclude: /(node_modules)/
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: ['url-loader?limit=100000']
},
{
test: /\.html$/,
use: [
'ngtemplate-loader',
'html-loader'
],
exclude: /(index)/
},
{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
},
],
},
node: {
fs: 'empty'
},
resolve: {
modules: [
__dirname,
'node_modules',
],
},
plugins: [
new CleanWebpackPlugin(['dist']),
new webpack.optimize.CommonsChunkPlugin({
name: 'common-dependencies',
}),
new ContextReplacementPlugin(
/(.+)?angular(\\|\/)core(.+)?/,
path.resolve(__dirname, '../src')
)
],
devtool: 'source-map',
externals: [],
devServer: {
historyApiFallback: true
}
};
我检查了其他关于的 SO 主题Unexpected token <
,我确定我的网络选项卡中没有 404 - Not found 错误。
解决方案
这从根本上解决了问题,不使用该templateUrl
属性来加载指令的模板,但我已经使用了这个 angularjs 和 webpack 配置,效果很好;它还通过内联模板来保存 HTTP 请求。
// webpack.config.js
module.exports = {
// ...
module: {
rules: [
// Load raw HTML files for inlining our templates
{ test: /\.(html)$/, loader: "raw-loader" },
// ... other rules, config, etc.
]
}
}
然后,在指令文件中:
import templateString from './wherever.template.html'
function directiveFunc() {
return {
// template, rather than templateUrl
template: templateString,
// ...
}
}
export default directiveFunc
安装raw-loader
装载机:
$ npm install raw-loader --save-dev
推荐阅读
- css - 媒体查询在 wordpress 中不起作用?
- bash - bash READLINE_LINE 在行继续后的函数中为空
- html - 我的表单代码显示在我的网站上而不是呈现?
- sql - PostgreSQL 多对多关系 SUM
- android - 当用户完成输入而不是在 kotlin android 中更改的文本时发送文本数据
- azure - 由于使用 StackExchange.Redis 的“ConnectTimeout”,无法连接到 Azure Redis 缓存
- python - 根据数据框的另一部分有条件地将一列拆分为多列
- reactive-programming - Webflux - 在条件后返回 Flux 或错误
- sql - 您如何使用 SQL 在 MS Access 中找到约束/外键/关系?
- azure-devops - 管道上缺少 Azure 订阅