我第一次尝试使用 webpack 时遇到了困难。
我在浏览器控制台中收到以下错误。
ERROR TypeError: $(...).sparkline is not a function
这是我的 webpack.config.vendor.js 代码
const path = require('path');
const webpack = require('webpack');
//const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'@angular/animations',
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/forms',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'zone.js/dist/zone',
];
const nonTreeShakableModules = [
'jquery',
'jquery-sparkline',
'.\\node_modules\\jquery-sparkline\\jquery.sparkline.js',
'@angular/material',
'event-source-polyfill',
'.\\wwwroot\\assets\\styles\\style.scss',
'.\\node_modules\\chartist\\dist\\chartist.css',
'.\\node_modules\\quill\\dist\\quill.snow.css',
'.\\node_modules\\quill\\dist\\quill.bubble.css',
'.\\node_modules\\angular-calendar\\css\\angular-calendar.css',
'.\\node_modules\\dragula\\dist\\dragula.css',
'.\\ClientApp\\styles.css',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { "modules": true
},
resolve: {
extensions: ['.js'],
},
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)esm5/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/20357
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
const clientBundleConfig = merge(sharedConfig, {
entry: {
// To keep development builds fast, include all vendor dependencies in the vendor bundle.
// But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
vendor: isDevBuild ? allModules : nonTreeShakableModules
},
output: { path: path.join(__dirname, 'wwwroot', 'dist') },
module: {
rules: [
{
test: /\.scss$/, use: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
},
//{
//test: /\.scss$/, use: ExtractTextPlugin.extract({
// use: ['css-loader', 'sass-loader'],
// // use style-loader in development
// fallback: "style-loader"
//})
//}
]
},
plugins: [
new webpack.DllPlugin({
context: __dirname,
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin()
])
});
const serverBundleConfig = merge(sharedConfig, {
target: 'node',
resolve: { mainFields: ['main'] },
entry: { vendor: allModules.concat(['aspnet-prerendering']) },
output: {
path: path.join(__dirname, 'ClientApp', 'dist'),
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.scss$/, use: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
},
//{
//test: /\.scss$/, use: ExtractTextPlugin.extract({
// use: ['css-loader', 'sass-loader'],
// // use style-loader in development
// fallback: "style-loader"
//})
//}
]
},
plugins: [
new webpack.DllPlugin({
context: __dirname,
path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return [clientBundleConfig, serverBundleConfig];
}
这是我的 webpack.config.js 代码。
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: true },
context: __dirname,
resolve: { extensions: ['.js', '.ts'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{
test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '@ngtools/webpack'
},
{
test: /\.html$/, use: 'html-loader?minimize=false'
},
{
test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
},
//{
// test: /\.scss$/, use: ExtractTextPlugin.extract({
// use: ['css-loader', 'sass-loader'],
// // use style-loader in development
// fallback: "style-loader"
// })
//},
{
test: /\.scss$/, use: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'
}
]
},
plugins: [
new ExtractTextPlugin({ filename: 'vendor.css', disable: false, allChunks: true }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new CheckerPlugin()
]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: {
'main-client': './ClientApp/boot.browser.ts'
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AngularCompilerPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/components/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AngularCompilerPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
我已经包含了 jquery-sparkline,但我仍然收到该错误。我可以在 vendor.js 中看到迷你图代码,但它似乎没有任何区别。
我还查看了 vendor list 文件,它包含这个但没有提到迷你图。
"./node_modules/jquery-sparkline/jquery.sparkline.js":{
"id":101,
"meta":{
}
}
我也不明白为什么我必须将下面的 ProvidePlugin 放在两个文件中。当然一次应该足够了,但是当它只在 vendor 文件中时,我收到浏览器错误,说它找不到 $。
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })
如有任何帮助,我们将不胜感激!
谢谢
最佳答案
看起来您正在使用 angular-netcore。
在这种情况下,您需要为迷你图安装types,因为还没有准备好,您必须创建一个。
ClientApp/typings/sparkline/index.d.ts
index.d.ts
// Generated by typings
// Source: ClientApp/typings/sparkline/index.d.ts
interface JQuery {
sparkline(values?: string | Array<(string | number)>, opts?: sparkline.Settings): any;
}
declare namespace sparkline {
interface Settings {
type?: string;
barColor?: string;
width?: string | number;
height?: string;
lineColor?: string;
fillColor?: string | number;
chartRangeMin?: string | number;
chartRangeMax?: string | number;
composite?: boolean;
enableTagOptions?: boolean;
tagOptionPrefix?: string;
tagValuesAttribute?: string;
disableHiddenCheck?: boolean;
}
}
接下来你需要向全局声明:
typings install --global --save file:./ClientApp/typings/sparkline/index.d.ts
如果你没有typings,你可以安装
yarn install typings
最后将 jquery-sparkline 添加到 boot.browser.ts
boot.browser.ts
import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import 'jquery-sparkline';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.browser.module';
...
因为 boot.browser.ts 是客户端包的配置,适合在浏览器中运行。
!!!重要
不要将 import 'jquery-sparkline'; 放入应用程序/组件,因为我们不想注入(inject)到 boot.server (会抛出错误原因服务器端预渲染)。
此处需要完整的代码示例:dotnet-core-angular-sparkline
关于javascript - 在 webpack 中包含 jquery-sparkline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440674/
rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送
Heroku支持人员告诉我,为了在我的Web应用程序中使用自定义字体(未安装在系统中,您可以在bash控制台中使用fc-list查看已安装的字体)我必须部署一个包含所有字体的.fonts文件夹里面的字体。问题是我不知道该怎么做。我的意思是,我不知道文件名是否必须遵循heroku的任何特殊模式,或者我必须在我的代码中做一些事情来考虑这种字体,或者如果我将它包含在文件夹中它是自动的......事实是,我尝试以不同的方式更改字体的文件名,但根本没有使用该字体。为了提供更多详细信息,我们使用字体的过程是将PDF转换为图像,更具体地说,使用rghostgem。并且最终图像根本不使用自定义字体。在
我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
我正在为锦标赛开发一个Rails应用程序。我在这个查询中使用了三个模型:classPlayertruehas_and_belongs_to_many:tournamentsclassTournament:destroyclassPlayerMatch"Player",:foreign_key=>"player_one"belongs_to:player_two,:class_name=>"Player",:foreign_key=>"player_two"在tournaments_controller的显示操作中,我调用以下查询:Tournament.where(:id=>params
我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan
我有:sprintf("%02X"%13)哪些输出:=>"OD"我希望我的输出是:=>"%0D"我试过:sprintf("\%%02X"%13)但我得到一个错误警告:格式字符串的参数过多。这同样适用于:sprintf("%%02X"%13)是否可以单独在sprintf中添加前导%? 最佳答案 文字%必须转义为%%:sprintf('%%')#=>"%"此外,您应该使用sprintf或%,而不是两者:sprintf('%%%02X',13)#=>"%0D"#^#commahere'%%%02X'%13#=>"%0D"#^#percen
我正在尝试将模块的单元测试包含在与模块本身相同的源文件中,遵循Perlmodulino模型。#!/usr/bin/envrubyrequire'test/unit'moduleModulinodefmodulino_functionreturn0endendclassModulinoTest现在,我可以运行执行此源文件的单元测试。但是,当我从另一个脚本需要/加载它们时,它们也会运行。如何避免这种情况?是否有更惯用的方法来使用Ruby实现此目的,除非不鼓励这种做法? 最佳答案 就我个人而言,我从未听说有人试图在Ruby中这样做。这绝对
我以为它已经安装了,但在我的gemfile中有gem"jquery-rails"但是在我的asset/javascripts文件夹中accounts.js.coffeeapplication.js都被注释掉了这是我的虚拟railsapplication但是在源代码中没有jQuery并且删除链接不起作用......任何想法都丢失了 最佳答案 看看thisRailscast.您可能需要检查application.js文件并确保它包含以下语句。//=requirejquery//=requirejquery_ujs
我想在页面顶部创建自定义Jquery消息而不是标准RailsFlash消息。我想在我的投票底部附近创建一条即时消息。我的Controller:defvote_up@post=Post.find(params[:id])current_user.up_vote(@post)flash[:message]='Thanksforvoting!'redirect_to(root_path,:notice=>'Takforditindlæg,deternuonline!')rescueMakeVoteable::Exceptions::AlreadyVotedErrorflash[:error]