我有一个Angular应用程序,目前是通过Webpack构建成一个大的捆绑包,在一个文件中包含所有依赖项和应用程序代码。我试图将代码分成两个包,一个包包含我所有的依赖项,另一个包包含我所有的应用程序代码。
我有以下webpack.config.js:
var webpack = require('webpack');
var path = require('path');
var definePlugin = new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `"${process.env.NODE_ENV}"`
}
});
var SRC = path.resolve(__dirname, 'src/main/client');
var APP = path.resolve(SRC, 'app/index.js');
var DEST = path.resolve(__dirname, 'target/webapp/dist');
module.exports = {
entry: {
vendor: [
'angular',
'angular-animate',
'moment',
'angular-moment',
'angular-translate',
'angular-ui-bootstrap',
'angular-ui-router',
'lodash'
],
app: APP
},
plugins: [
new webpack.ProvidePlugin({
_: 'lodash',
angular: 'angular',
angularMoment: 'angular-moment',
angularTranslate: 'angular-translate',
moment: 'moment',
ngAnimate: 'angular-animate',
uibootstrap: 'angular-ui-bootstrap',
uirouter: 'angular-ui-router'
}),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
definePlugin
],
output: {
path: DEST,
filename: 'bundle.js',
publicPath: '/',
hash: true
},
module: {
preLoaders: [],
loaders: [
{ test: /\.html$/, loaders: ['html'] },
{ test: /\.css$/, loaders: ['style', 'css'] },
{ test: /\.scss$/, loaders: ['style', 'css', 'sass'] },
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loaders: ['ng-annotate', 'babel?presets[]=es2015', 'eslint']
},
{
test: /\.(ttf|eot|svg|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file'
}
]
},
sassLoader: {
includePaths: [path.resolve(__dirname, './node_modules')]
}
};这会产生两个包,一个只包含依赖项,另一个只包含应用程序代码。然而,当我试图加载应用程序时,我得到了:Uncaught TypeError: angular.module is not a function,它可以追溯到vendor.bundle.js中的angular-moment.js。换句话说,需要加载到vendor.bundle.js文件中的其他模块无法访问angular。但是,我不确定如何使这些依赖项彼此可见。
发布于 2017-01-10 16:32:22
要回答原始帖子标题中的问题,Angular 1在没有垫片的情况下与webpack不能很好地工作(参见https://github.com/webpack/webpack/issues/2049)。试试这个webpack的加载器配置:
module: {
loaders: [
/*
* Necessary to be able to use angular 1 with webpack as explained in https://github.com/webpack/webpack/issues/2049
*/
{
test: require.resolve('angular'),
loader: 'exports?window.angular'
},
]
},
plugins: [
new webpack.ProvidePlugin({
'angular': 'angular',
}),
],这应该会正确地初始化angular对象,而不是将其设置为空对象(没有名为module的属性)的默认操作。
发布于 2016-11-29 13:31:40
下面应该将所有不在src文件夹中的脚本移动到供应商块中。
const path = require('path');
const projectRoot = path.resolve('./');
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: (module) => module.resource && module.resource.indexOf(path.join(projectRoot, 'src')) === -1,
}),https://stackoverflow.com/questions/39023407
复制相似问题