gpt4 book ai didi

angularjs - Webpack导入html模板未加载

转载 作者:行者123 更新时间:2023-12-02 22:27:42 25 4
gpt4 key购买 nike

我有一个使用 Webpack 用 AngularJS 制作的整体项目,但我收到一条错误消息:Unexpected token < main.html.当我的一个 Controller 中有这行代码时,就会发生此错误:

 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
}
};

我已经检查了有关 Unexpected token < 的其他主题,我确信我的网络选项卡中没有 404 - 未找到错误。

最佳答案

这从根本上从不同的 Angular 解决了这个问题,不使用 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

关于angularjs - Webpack导入html模板未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51399886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com