我的Angular 2.0.2应用程序使用Webpack。我有一个vendors.ts
文件,我在其中导入我想要使用的外部JavaScript。
示例(在vendors.ts中):
import '../node_modules/moment/min/moment-with-locales.min.js';
执行此操作后,我的供应商包文件包含“Moment JS”代码,但我无法在我的应用程序中使用它。
它说:
dateFormat需要momentjs。请在你的HTML中添加“&gt ;. 例外:时刻未定义
如果我在index.html
文件中手动添加对脚本标记的引用,那么一切正常。我对所有外部加载的库都有同样的问题,而不只是“Moment JS”。
这是我的整个webpack配置:
// Core stuff
var path = require('path');
var webpack = require('webpack');
// Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
// Get NPM lifecycle event to identify the environment
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig() {
// This is the object where all configuration gets set
var config = {};
// Devltool (http://webpack.github.io/docs/configuration.html#devtool)
// Type of sourcemap to use per build type
if (isProd) {
config.devtool = 'source-map';
} else if (isTest) {
config.devtool = 'inline-source-map';
}
else {
config.devtool = 'eval-source-map';
}
// Entry (http://webpack.github.io/docs/configuration.html#entry)
config.entry = isTest ? {} : {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
};
// Output (http://webpack.github.io/docs/configuration.html#output)
config.output = isTest ? {} : {
path: root('dist'),
publicPath: isProd ? '/' : 'http://localhost:3000/',
filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
};
// Resolve (http://webpack.github.io/docs/configuration.html#resolve)
config.resolve = {
extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'], // Only discover files that have those extensions
};
var atlOptions = '';
if (isTest && !isTestWatch) {
atlOptions = 'inlineSourceMap=true&sourceMap=false'; // "awesome-typescript-loader" needs to output inlineSourceMap for code coverage to work with source maps
}
// Loaders (http://webpack.github.io/docs/configuration.html#module-loaders)
config.module = {
rules: [
// Support for TypeScript (.ts) files
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader?' + atlOptions,
'angular2-template-loader',
'@angularclass/hmr-loader',
'angular2-router-loader'
],
exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
},
// Copy assets to output
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file?name=fonts/[name].[hash].[ext]?'
},
// Support for *.json files.
{
test: /\.json$/,
loader: 'json'
},
// Support for CSS as raw text
// use 'null' loader in test mode (https://github.com/webpack/null-loader)
// all css in src/style will be bundled in an external css file
{
test: /\.css$/,
exclude: root('src', 'app'),
loader: isTest ? 'null' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css', 'postcss']})
},
// support for .scss files
// use 'null' loader in test mode (https://github.com/webpack/null-loader)
// all css in src/style will be bundled in an external css file
{
test: /\.scss$/,
exclude: root('src', 'app'),
loader: isTest ? 'null' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css', 'postcss', 'sassLoader']})
},
// Support for .html as raw text
{
test: /\.html$/,
loader: 'raw',
exclude: root('src', 'public')
}
]
};
if (isTest && !isTestWatch) {
// instrument only testing sources with Istanbul, covers ts files
config.module.rules.push({
test: /\.ts$/,
enforce: 'post',
include: path.resolve('src'),
loader: 'istanbul-instrumenter-loader',
exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
});
}
if (!isTest || !isTestWatch) {
// tslint support
config.module.rules.push({
test: /\.ts$/,
enforce: 'pre',
loader: 'tslint'
});
}
// Plugins (http://webpack.github.io/docs/configuration.html#plugins)
config.plugins = [
// Define env variables to help with builds (https://webpack.github.io/docs/list-of-plugins.html#defineplugin)
new webpack.DefinePlugin({
'process.env': {
ENV: JSON.stringify(ENV)
}
}),
// Workaround needed for Angular 2 (angular/angular#11580)
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, root('./src')),
// Tslint configuration for Webpack 2
new webpack.LoaderOptionsPlugin({
options: {
// Apply the tslint loader as pre/postLoader (https://github.com/wbuchwalter/tslint-loader)
tslint: {
emitErrors: false,
failOnHint: false
},
// Sass (https://github.com/jtangelder/sass-loader)
sassLoader: {
//includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
},
//PostCSS (https://github.com/postcss/autoprefixer-core)
postcss: [
autoprefixer({
browsers: ['last 2 version']
})
]
}
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
})
];
if (!isTest && !isProd) {
config.plugins.push(new DashboardPlugin());
}
if (!isTest && !isTestWatch) {
config.plugins.push(
new ForkCheckerPlugin(),
// Generate common chunks if necessary (https://webpack.github.io/docs/code-splitting.html - https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin)
new CommonsChunkPlugin({
name: ['vendor', 'polyfills']
}),
// Inject script and link tags into html files (https://github.com/ampedandwired/html-webpack-plugin)
new HtmlWebpackPlugin({
template: './src/public/index.html',
chunksSortMode: 'dependency'
}),
// Extract css files (https://github.com/webpack/extract-text-webpack-plugin)
new ExtractTextPlugin({filename: 'css/[name].[hash].css', disable: !isProd})
);
}
// Add build specific plugins
if (isProd) {
config.plugins.push(
// Only emit files when there are no errors (http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin)
new webpack.NoErrorsPlugin(),
// Dedupe modules in the output (http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin)
// new webpack.optimize.DedupePlugin(),
// Minify all javascript, switch loaders to minimizing mode (http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin)
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
mangle: {
keep_fnames: true
}
}),
// Copy assets from the public folder (https://github.com/kevlened/copy-webpack-plugin)
new CopyWebpackPlugin([{
from: root('src/public')
}])
);
}
// Dev server configuration (http://webpack.github.io/docs/configuration.html#devserver - http://webpack.github.io/docs/webpack-dev-server.html)
config.devServer = {
contentBase: './src/public',
historyApiFallback: true,
quiet: true,
stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
};
return config;
}();
// Helper functions
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
我做错了什么?
答案 0 :(得分:0)
据我所知,您不需要在vendors.ts文件中添加node_modules
文件夹。
使用do:moment/min/moment-with-locales.min.js
另外,你的Webpack配置似乎并没有真正有序。我没有看到.entry
或.resolve
等。
也许你应该尝试一些Angular webpack启动器: