如何在生产中的Webpack项目中使用CDN中的库 [英] How to use a library from a CDN in a Webpack project in production
问题描述
我想在生产中使用CDN中的 react.min.js
(例如 https://unpkg.com/react@15.3.1/dist/react.min.js )
I'd like to use react.min.js
from a CDN in production (e.g. https://unpkg.com/react@15.3.1/dist/react.min.js)
使Webpack将我的导入React从'react'
语句转换为 const React = window的最佳方法是什么反应
而不是将 node_modules / react
构建到捆绑包中?
What is the best way to get Webpack to transform my import React from 'react'
statements into const React = window.React
instead of building node_modules/react
into the bundle?
我一直使用 resolve.alias
来做到这一点:
I've been doing it with resolve.alias
like this:
在 index.html
中:
<head>
<script type="text/javascript" src="https://unpkg.com/react@15.3.1/dist/react.min.js"></script>
<script type="text/javascript" src="/assets/bundle.js"></script>
</head>
在 webpack.prod.config.js
:
alias: {
react$: './getWindowReact',
},
getWindowReact.js
:
module.exports = window.React;
注意:在旧问题中,我没有意识到构建React放入具有 NODE_ENV = production
的Webpack捆绑包中,将除去 propTypes
支票。答案之一就是针对这一点。
Note: In the old question I didn't realize that building React into a Webpack bundle with NODE_ENV=production
would strip out the propTypes
checks. One of the answers focuses on that.
推荐答案
在您的webpack配置中,您可以使用 externals
选项将从环境中导入模块,而不是尝试正常解决该问题:
In your webpack config you can use the externals
option which will import the module from the environment instead of trying to resolve it normally:
// webpack.config.js
module.exports = {
externals: {
'react': 'React'
}
...
};
在此处了解更多信息:
https://webpack.js.org/configuration/externals/
Read more here: https://webpack.js.org/configuration/externals/
这篇关于如何在生产中的Webpack项目中使用CDN中的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!