gpt4 book ai didi

javascript - 使用 webpack 导入 angularjs 的最佳实践是什么?

转载 作者:IT王子 更新时间:2023-10-29 03:00:33 24 4
gpt4 key购买 nike

Webpack和AngularJS如何结合使用,模板加载和按需获取资源如何?

非常感谢为此目的编写良好的 webpack.config.js 文件示例。

此处显示的所有代码片段均可在 this github repo 访问.代码已大量改编自 this packetloop git repo .

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;

要将 AngularJS 导入到主 app.js 中,您需要执行以下操作:

app/vendor/angular.js

'use strict';

if (!global.window.angular) {
require('bower/angular/angular');
}
var angular = global.window.angular;
module.exports = angular;

然后像这样在app.js中使用它,

app.js

...
var angular = require('vendor/angular');

// Declare app level module
var app = angular.module('myApp', []);

...

以下是正确的吗?有没有更简单的方法来做到这一点?我看过一些(以任何标准衡量都不算多)列出另一种方法的帖子。

来自 this reddit post comment

// Add to webpack.config.js#module#loaders array
{
test: /[\/]angular\.js$/,
loader: "exports?angular"
}

还有另一个正在开发中的插件,地址为 stackfull/angular-seed .它似乎是在正确的方向,但现在真的很难使用。

Webpack 非常棒,但缺乏文档和示例正在扼杀它。

最佳答案

您可以在所有需要的模块(文件)中只需要 angular。我有一个 github repository举例说明如何做到这一点(也使用 webpack 进行构建)。在示例中使用了 ES6 导入语法,但没关系,您可以改用标准的 require()

示例:

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

关于javascript - 使用 webpack 导入 angularjs 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648255/

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