Javascript 使用 webpack 导入 angularjs 的最佳实践是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28648255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best practice for importing angularjs using webpack?
提问by Jibi Abraham
How do you use Webpack and AngularJS together, and how about template loading and on demand fetching of resources?
你如何将 Webpack 和 AngularJS 一起使用,以及模板加载和按需获取资源如何?
An example of a well written webpack.config.jsfile for this purpose would be very much appreciated.
webpack.config.js非常感谢为此目的编写好的文件示例。
All code snippets displayed here can be accessed at this github repo. Code has been generously adapted from this packetloop git repo.
此处显示的所有代码片段都可以在此 github repo 中访问。代码已经大量改编自这个 packetloop git repo。
webpack.config.json
webpack.config.json
var path = require('path');
var ResolverPlugin = require("webpack/lib/ResolverPlugin");
var config = {
context: __dirname,
entry: ['webpack/hot/dev-server', './app/app.js'],
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.css$/,
loader: "style!css-loader"
}, {
test: /\.scss$/,
loader: "style!css!sass?outputStyle=expanded"
}, {
test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,
loader: "file"
}, {
test: /\.html$/,
loader: "ngtemplate?relativeTo=" + path.join(__dirname, 'app/') + "!raw"
}]
},
// Let webpack know where the module folders are for bower and node_modules
// This lets you write things like - require('bower/<plugin>') anywhere in your code base
resolve: {
modulesDirectories: ['node_modules', 'lib/bower_components'],
alias: {
'npm': __dirname + '/node_modules',
'vendor': __dirname + '/app/vendor/',
'bower': __dirname + '/lib/bower_components'
}
},
plugins: [
// This is to help webpack know that it has to load the js file in bower.json#main
new ResolverPlugin(
new ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
)
]
};
module.exports = config;
To import AngularJS into the main app.jsyou do the following:
要将 AngularJS 导入到 main 中,app.js请执行以下操作:
app/vendor/angular.js
应用程序/供应商/angular.js
'use strict';
if (!global.window.angular) {
require('bower/angular/angular');
}
var angular = global.window.angular;
module.exports = angular;
And then use it in app.jslike so,
然后app.js像这样使用它,
app.js
应用程序.js
...
var angular = require('vendor/angular');
// Declare app level module
var app = angular.module('myApp', []);
...
Is the following correct? Is there an easier way to do this? I've seen a few (not a lot by any standards) posts which listed another method.
以下是否正确?有没有更简单的方法来做到这一点?我看过一些(按照任何标准都不是很多)列出另一种方法的帖子。
// Add to webpack.config.js#module#loaders array
{
test: /[\/]angular\.js$/,
loader: "exports?angular"
}
There is also another plugin which is in development right now, at stackfull/angular-seed. It seems to be in the right direction, but is really really hard to use right now.
还有另一个插件正在开发中,位于stackfull/angular-seed。它似乎是在正确的方向,但现在真的很难使用。
Webpack is way awesome, but the lack of documentation and samples are killing it.
Webpack 非常棒,但缺乏文档和示例正在扼杀它。
回答by tomastrajan
You can just require angular in all modules (files) where you need it. I have a github repositorywith example how to do that (also using webpack for build). In the example ES6 import syntax is used but it shouldnt matter, you can use standard require()instead.
您可以在需要的所有模块(文件)中只要求 angular。我有一个github 存储库,其中包含如何执行此操作的示例(也使用 webpack 进行构建)。在示例中使用了 ES6 导入语法,但没关系,您可以使用标准require()代替。
Example:
例子:
import 'bootstrap/dist/css/bootstrap.min.css';
import './app.css';
import bootstrap from 'bootstrap';
import angular from 'angular';
import uirouter from 'angular-ui-router';
import { routing} from './app.config';
import common from './common/common.module';
import featureA from './feature-a/feature-a.module';
import featureB from './feature-b/feature-b.module';
const app = angular
.module('app', [uirouter, common, featureA, featureB])
.config(routing);
回答by Kamil
I am starting with Angular + Fluxwith Webpackso may be I can help you with some things.
我开始Angular + Flux用Webpack,可能是我可以帮你一些事情。
Basically I am installing everything with NPM, it has module exportsystem, so it works like nothing. (You can use export-loader, but why if you do not need to.)
基本上我正在安装所有东西NPM,它有module export系统,所以它什么都没有。(您可以使用export-loader,但如果您不需要,为什么?)
My webpack.config.jslooks like this:
我的webpack.config.js看起来像这样:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require("html-webpack-plugin");
var nodeModulesDir = path.resolve(__dirname, './node_modules');
// Some of my dependencies that I want
// to skip from building in DEV environment
var deps = [
'angular/angular.min.js',
...
];
var config = {
context: path.resolve(__dirname, './app'),
entry: ['webpack/hot/dev-server', './main.js'],
resolve: {
alias: {}
},
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js'
},
// This one I am using to define test dependencies
// directly in the modules
plugins: [
new webpack.DefinePlugin({
ON_TEST: process.env.NODE_ENV === 'test'
})
],
module: {
preLoaders: [
{test: /\.coffee$/, loader: "coffeelint", exclude: [nodeModulesDir]}
],
loaders: [
{test: /\.js$/, loader: 'ng-annotate', exclude: [nodeModulesDir]},
{test: /\.coffee$/, loader: 'coffee', exclude: [nodeModulesDir]},
...
],
noParse: []
},
devtool: 'source-map'
};
if (process.env.NODE_ENV === 'production') {
config.entry = {
app: path.resolve(__dirname, './app/main.js'),
vendors: ['angular']
};
// config.output.path = path.resolve(__dirname, './dist');
config.output = {
path: path.resolve(__dirname, "./dist"),
filename: "app.[hash].js",
hash: true
};
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.[hash].js'));
config.plugins.push(new HtmlWebpackPlugin({
title: 'myApp',
template: path.resolve(__dirname, './app/index.html'),
inject: 'body'
}));
delete config.devtool;
}
else {
deps.forEach(function (dep) {
var depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
}
module.exports = config;
My main.jslooks like this:
我的main.js看起来像这样:
var angular = require('angular');
if(ON_TEST) {
require('angular-mocks/angular-mocks');
}
require('./index.coffee');
And index.coffeecontaint main angular module:
和index.coffee 包含主角度模块:
ngModule = angular.module 'myApp', []
require('./directive/example.coffee')(ngModule)

