首页 > 解决方案 > 加载一个与捆绑包分开的库

问题描述

我正在尝试使用这个库,但这取决于THREE.js已经在全球范围内加载。我正在使用typescript,webpackwebpack-dev-server. 是否可以在主包之前将 webpackTHREE.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"
  ]
}

标签: typescriptwebpackwebpack-dev-server

解决方案


可能值得将 CDN 链接three.js添加到您绑定到的 html 模板中webpack。看起来这是您的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>

推荐阅读