从捆绑包中单独加载一个库



>我正在尝试使用此库,但这取决于THREE.js已经全局加载。我正在使用typescriptwebpackwebpack-dev-server。是否可以在主捆绑包之前将 webpack 加载THREE.js作为单独的脚本?我还需要在自己的源代码中使用THREE,所以我也想将其完全从主捆绑包中排除。

这是我的webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-sourcemap',
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 4500
},
module: {
rules: [
{
test: /.tsx?$/i,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /.obj$/i,
use: {
loader: 'file-loader'
},
},
{
test: /.css$/i,
use: ['style-loader', 'css-loader'],
}
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist'
},
plugins: [new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.ejs'
})]
};

还有我的tsconfig.json:

{
"compilerOptions": {
"baseUrl": ".",
"outDir": "./dist/",
"noImplicitAny": false,
"module": "es6",
"target": "es2015",
"sourceMap": true,
"moduleResolution": "node",
"allowJs": true,
"typeRoots": [
"src/types",
"node_modules/@types"
],
"paths": {
"@custom-modules/*": ["src/types/*"]
}
},
"exclude": [
"node_modules",
"src/types"
]
}

可能值得将 CDN 链接带到three.js并将其添加到您在webpack中绑定到的 html 模板中。看起来这是您的index.ejs文件。

我不确定您如何构建此文件,但在 html 中它看起来像:

<!DOCTYPE html>
<html>
<head>
...
// globally add three.js to your site
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
// put the rest of your scripts below
...
</head>
<body><!-- Your web--></body>
</html>

我通过在 webpack 配置中添加three.jsexternals并通过 CDN 包含它来解决这个问题。

最新更新