假设我们从以下入门包开始: https://github.com/angularclass/angular2-webpack-starter
在 npm install
和 npm run start
之后一切正常。
我想添加一个外部 css 模块,例如 bootstrap 4 的 css(而且只有 css)。 (我知道 bootstrap 有一个 bootstrap-loader,但现在我要求的是通用解决方案,所以请在这里考虑 bootstrap 4,因为它可能是通过 npm 可用的任何其他 css 模块)。
我通过 npm 安装 bootstrap:npm install bootstrap@4.0.0-alpha.4 --save
首先我认为添加 import 'bootstrap/dist/css/bootstrap.css';
到 vendor.browser.ts 文件就足够了。
但事实并非如此。
我应该怎么做才能找到合适的解决方案?
我不要求的解决方案:
- “将外部 css 模块复制到 Assets 文件夹,并从那里使用它”
- 我正在寻找与 npm 包一起工作的解决方案。
- “为 webpack 使用 bootstrap-loader”
- 正如我上面所描述的,我正在寻找一个通用的解决方案,bootstrap 在这里只是一个例子。
- “使用另一个堆栈”
- 我正在寻找与我上面提到的完全相同的入门包中的解决方案。
最佳答案
可以通过在 styles.css 文件上使用 @import '~bootstrap/dist/css/bootstrap.css';
来实现。 (注意 ~)
编辑:它是如何工作的——“~”是在指向 Assets 文件夹的 webpack 配置上设置的别名……就这么简单……
编辑 2:有关如何使用“~”别名配置 webpack 的示例...
这应该放在 webpack 配置文件中(通常是 webpack.config.js
)...
// look for the "resolve" property and add the following...
// you might need to require the asset like '~/bootsrap/...'
resolve: {
alias: {
'~': path.resolve('./node_modules')
}
}
关于css - 如何从 webpack angular2 应用程序中的 node_modules 导入 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071845/